Java Reference
In-Depth Information
To keep elements sorted, use a
TreeSet
. To keep elements in the order in which
you inserted them, use a
LinkedList, ArrayList
, or array.
Step 3 Determine which operations must be fast.
You have several choices.
ȗ It doesn't matter. You collect so few elements that you aren't concerned
about speed.
ȗ Adding and removing elements must be fast.
ȗ Finding elements must be fast.
737
738
Linked lists allow you to add and remove elements efficiently, provided you are
already near the location of the change. Changing either end of the linked list is
always fast.
If you need to find an element quickly, use a set.
At this point, you should have narrowed down your selection to a particular
container. If you answered ȒIt doesn't matterȓ for each of the choices, then just use
an
ArrayList
. It's a simple container that you already know well.
Step 4 For sets and maps, choose between hash tables and trees.
If you decided that you need a set or map, you need to pick a particular
implementation, either a hash table or a tree.
If your elements (or keys, in case of a map) are strings, use a hash table. It's more
efficient.
If your elements or keys belong to a type that someone else defined, check whether
the class implements its own
hashCode
and
equals
methods. The inherited
hashCode
method of the
Object
class takes only the object's memory address
into account, not its contents. If there is no satisfactory
hashCode
method, then
you must use a tree.
If your elements or keys belong to your own class, you usually want to use
hashing. Define a
hashCode
and compatible
equals
method.