Java Reference
In-Depth Information
14. Suppose we define a coin comparator whose compare method always
returns 0. Would the TreeSet function correctly?
H OW T O 16.1: Choosing a Container
Suppose you need to store objects in a container. You have now seen a number of
different data structures. This How To reviews how to pick an appropriate
container for your application.
Step 1 Determine how you access the elements.
You store elements in a container so that you can later retrieve them. How do you
want to access individual elements? You have several choices.
ȗ It doesn't matter. Elements are always accessed Ȓin bulkȓ, by visiting all
elements and doing something with them.
ȗ Access by key. Elements are accessed by a special key. Example: Retrieve a
bank account by the account number.
ȗ Access by integer index. Elements have a position that is naturally an integer
or a pair of integers. Example: A piece on a chess board is accessed by a row
and column index.
If you need keyed access, use a map. If you need access by integer index, use an
array list or array. For an index pair, use a two-dimensional array.
Step 2 Determine whether element order matters.
When you retrieve elements from a container, do you care about the order in which
they are retrieved? You have several choices.
ȗ It doesn't matter. As long as you get to visit all elements, you don't care in
which order.
ȗ Elements must be sorted.
ȗ Elements must be in the same order in which they were inserted.
Search WWH ::




Custom Search