Java Reference
In-Depth Information
This way, you have to change only one line if you decide to use a
TreeSet
instead.
Also, methods that operate on sets should specify parameters of type
Set
:
public static void print(
Set
<String> s)
Then the method can be used for all set implementations.
In theory, we should make the same recommendation for linked lists, namely to
save
LinkedList
references in variables of type
List
. However, in the Java
library, the
List
interface is common to both the
ArrayList
and the
LinkedList
class. In particular, it has
get
and
set
methods for random
access, even though these methods are very inefficient for linked lists. You c
an't
write efficient code if you don't know whether random access is efficient o
r not.
This is plainly a serious design error in the standard library, and I cannot
recommend using the
List
interface for that reason. (To see just how
embarrassing that error is, have a look at the source code for the
binarySearch
method of the
Collections
class. That method takes a
List
parameter, but
binary search makes no sense for a linked list. The code then clumsily tries to
discover whether the list is a linked list, and then switches to a linear search!)
704
705
The
Set
interface and the
Map
interface, which you will see in the next section,
are well-designed, and you should use them.
16.2 Maps
A map is a data type that keeps associations between keys and values.
Figure 3
gives a
typical example: a map that associates names with colors. This map might describe
the favorite colors of various people.
A map keeps associations between key and value objects.
Mathematically speaking, a map is a function from one set, the key set, to another set,
the value set. Every key in the map has a unique value, but a value may be associated
with several keys.