Java Reference
In-Depth Information
Figure 6.35 illustrates a
SimpleStudent
class in which two
SimpleStudent
s
are equal if they have the same name (and are both
SimpleStudent
s). This could
be overridden using the techniques in Figure 6.34 as needed, or this method
could be declared
final
. If it was declared
final
, then the test that is present
allows only two identically typed
SimpleStudent
s to be declared equal. If, with
a final
equals
, we replace the test at line 40 with an
instanceof
test, then any
two objects in the hierarchy can be declared equal if their names match.
The
hashCode
method at lines 47 and 48 simply uses the
hashCode
of the
name
field. Thus if two
SimpleStudent
objects have the same name (as declared
by
equals
) they will have the same
hashCode
, since, presumably, the implemen-
tors of
String
honored the contract for
hashCode
.
The accompanying test program is part of a larger test that illustrates all
the basic containers. Observe that if
hashCode
is unimplemented, all three
SimpleStudent
objects will be added to the
HashSet
because the duplicate will
not be detected.
It turns out that on average, the
HashSet
operations can be performed
in constant time. This seems like an astounding result because it means that
the cost of a single
HashSet
operation does not depend on whether the
HashSet
contains 10 items or 10,000 items. The theory behind the
HashSet
is fascinating
and is described in Chapter 20.
maps
6.8
A
Map
is used to store a collection of entries that consists of
keys
and their
val-
ues
. The
Map
maps keys to values. Keys must be unique, but several keys can
map to the same value. Thus, values need not be unique. There is a
SortedMap
interface that maintains the map logically in key-sorted order.
Not surprisingly, there are two implementations: the
HashMap
and
TreeMap
.
The
HashMap
does not keep keys in sorted order, whereas the
TreeMap
does. For
simplicity, we do not implement the
SortedMap
interface but we do implement
HashMap
and
TreeMap
.
The
Map
can be implemented as a
Set
instantiated with a
pair
(see
Section 3.9), whose comparator or
equals
/
hashCode
implementation refers
only to the key. The
Map
interface does not extend
Collection
; instead it
exists on its own. A sample interface that contains the most important
methods is shown in Figures 6.36 and 6.37.
Most of the methods have intuitive semantics.
put
is used to add a key/
value pair,
remove
is used to remove a key/value pair (only the key is speci-
fied), and
get
returns the value associated with a key.
null
values are allowed,
which complicates issues for
get
, because the return value from
get
will not
A
Map
is used to
store a collection
of entries that
consists of
keys
and their
values
.
The
Map
maps keys
to values.
Search WWH ::
Custom Search