Java Reference
In-Depth Information
{
return name+" "+age;
}
}
Listing 5-21 ' s main() method creates IdentityHashMap and HashMap in-
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
copying.” (I discuss serialization in Chapter 8 . ) It also states the following: “another
typical use of this class is to maintain proxy objects.” Also, developers responding
to stackoverflow's “Use Cases for Identity HashMap” topic ( ht-
tp://stackoverflow.com/questions/838528/use-cases-for-
identity-hashmap ) mention that it is much faster to use IdentityHashMap
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
Search WWH ::




Custom Search