Java Reference
In-Depth Information
{
return name+" "+age;
}
}
stancesthateachstoreanentryconsistingofan
Employee
keyanda
String
value.
Because
Employee
instancesaremutable(becauseof
setAge()
and
setName()
),
main()
changes their ages while these keys are stored in their maps. These changes
result in the following output:
{John Doe 28=SALES}
{Jane Doe 26=MGMT}
map1 contains key e1 = true
map2 contains key e2 = true
{John Doe 29=SALES}
{Jane Doe 27=MGMT}
map1 contains key e1 = true
map2 contains key e2 = false
The last four lines show that the changed entries remain in their maps. However,
map2
's
containsKey()
method reports that its
HashMap
instance no longer con-
tains its
Employee
key (which should be
Jane Doe 27
), whereas
map1
's
con-
tainsKey()
method reports that its
IdentityHashMap
instance still contains its
Employee
key, which is now
John Doe 29
.
Note
IdentityHashMap
'sdocumentation states that“atypical useofthisclass
is topology-preserving object graph transformations, such as serialization or deep
typical use of this class is to maintain proxy objects.” Also, developers responding
to stackoverflow's “Use Cases for Identity HashMap” topic (
ht-
than
HashMap
when the keys are
Class
objects.
WeakHashMap
The
WeakHashMap
class provides a
Map
implementation that is based on weakly
reachable keys. Because each key object is stored indirectly as the referent of a weak