Java Reference
In-Depth Information
21.8.3.
IdentityHashMap
The general contract of
Map
requires that equality for keys be based on
equivalence (that is, using the
equals
method). But there are times when
you really want a map that stores information about specific objects in-
stead of treating all equivalent objects as a single key to information.
Consider the serialization mechanism discussed in
Chapter 20
.
When de-
termining if an object in the serialization graph has already been seen,
you need to check that it is the actual object, not just one that is equi-
valent. To support such requirements the
IdentityHashMap
class uses ob-
ject identity (comparison using
==
) to determine if a given key is already
present in the map. This is useful, but it does break the general contract
of
Map
.
There are three constructors:
public
IdentityHashMap(int expectedSize)
Creates a new
IdentityHashMap
with the given expected max-
imum size.
public
IdentityHashMap()
Creates a new
IdentityHashMap
with the default expected max-
imum size.
public
IdentityHashMap(Map<? extends K, ? extends V> map)
Creates a new
IdentityHashMap
containing the entries from the
given map.
The expected maximum size is a hint for the initial capacity of the map,
but its exact effects are not specified.