Top Description Inners Fields Constructors Methods
java.util

public Class IdentityHashMap<K, V>

extends AbstractMap<K, V>
implements Map<K, V>, Serializable, Cloneable
Class Inheritance
All Implemented Interfaces
java.lang.Cloneable, java.io.Serializable, java.util.Map
Type Parameters
<K>
the type of keys maintained by this map
<V>
the type of mapped values
Imports
java.io.ObjectInputStream, .ObjectOutputStream, java.lang.reflect.Array, java.util.function.BiConsumer, .BiFunction, .Consumer, jdk.internal.access.SharedSecrets

This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)

This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.

The view collections of this map also have reference-equality semantics for their elements. See the keySet, values, and entrySet methods for further information.

A typical use of this class is topology-preserving object graph transformations, such as serialization or deep-copying. To perform such a transformation, a program must maintain a "node table" that keeps track of all the object references that have already been processed. The node table must not equate distinct objects even if they happen to be equal. Another typical use of this class is to maintain proxy objects. For example, a debugging facility might wish to maintain a proxy object for each object in the program being debugged.

This class provides all of the optional map operations, and permits null values and the null key. This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

This class provides constant-time performance for the basic operations (get and put), assuming the system identity hash function (System#identityHashCode(Object)) disperses elements properly among the buckets.

This class has one tuning parameter (which affects performance but not semantics): expected maximum size. This parameter is the maximum number of key-value mappings that the map is expected to hold. Internally, this parameter is used to determine the number of buckets initially comprising the hash table. The precise relationship between the expected maximum size and the number of buckets is unspecified.

If the size of the map (the number of key-value mappings) sufficiently exceeds the expected maximum size, the number of buckets is increased. Increasing the number of buckets ("rehashing") may be fairly expensive, so it pays to create identity hash maps with a sufficiently large expected maximum size. On the other hand, iteration over collection views requires time proportional to the number of buckets in the hash table, so it pays not to set the expected maximum size too high if you are especially concerned with iteration performance or memory usage.

Note that this implementation is not synchronized. If multiple threads access an identity hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

  Map m = Collections.synchronizedMap(new IdentityHashMap(...));

The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: fail-fast iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Implementation Note

This is a simple linear-probe hash table, as described for example in texts by Sedgewick and Knuth. The array contains alternating keys and values, with keys at even indexes and values at odd indexes. (This arrangement has better locality for large tables than does using separate arrays.) For many Java implementations and operation mixes, this class will yield better performance than HashMap, which uses chaining rather than linear-probing.

Author
Doug Lea and Josh Bloch
Since
1.4
See Also
System#identityHashCode(Object), Object#hashCode(), Collection, Map, HashMap, TreeMap

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
private class
pack-priv static class
private abstract class
pack-priv static class
IdentityHashMap.IdentityHashMapSpliterator<K, V>

Similar form as array-based Spliterators, but skips blank elements, and guestimates size as decreasing by half per split.

private class
private class
pack-priv static class
private class
private class
pack-priv static class

Field Summary

Modifier and TypeField and Description
private static final int
DEFAULT_CAPACITY

The initial capacity used by the no-args constructor.

private transient Set<Map.Entry<K, V>>
entrySet

This field is initialized to contain an instance of the entry set view the first time this view is requested.

private static final int
MAXIMUM_CAPACITY

The maximum capacity, used if a higher value is implicitly specified by either of the constructors with arguments.

private static final int
MINIMUM_CAPACITY

The minimum capacity, used if a lower value is implicitly specified by either of the constructors with arguments.

pack-priv transient int
modCount

The number of modifications, to support fast-fail iterators

pack-priv static final Object
NULL_KEY

Value representing null keys inside tables.

private static final long
pack-priv int
size

The number of key-value mappings contained in this identity hash map.

pack-priv transient Object[]
table

The table, resized as necessary.

Inherited from java.util.AbstractMap:
keySetvalues

Constructor Summary

AccessConstructor and Description
public
IdentityHashMap()

Constructs a new, empty identity hash map with a default expected maximum size (21).

public
IdentityHashMap(int
the expected maximum size of the map
expectedMaxSize
)

Constructs a new, empty map with the specified expected maximum size.

public
IdentityHashMap(Map<? extends K, ? extends V>
the map whose mappings are to be placed into this map
m
)

Constructs a new identity hash map containing the keys-value mappings in the specified map.

Method Summary

Modifier and TypeMethod and Description
private static int
capacity(int expectedMaxSize)

Returns the appropriate capacity for the given expected maximum size.

public void
clear()

Overrides java.util.AbstractMap.clear.

Implements java.util.Map.clear.

Removes all of the mappings from this map.

public Object

Returns:

a shallow copy of this map
clone
()

Overrides java.util.AbstractMap.clone.

Returns a shallow copy of this identity hash map: the keys and values themselves are not cloned.

private void
closeDeletion(int
the index of a newly empty deleted slot
d
)

Rehash all possibly-colliding entries following a deletion.

public boolean

Returns:

true if the specified object reference is a key in this map
containsKey
(Object
possible key
key
)

Overrides java.util.AbstractMap.containsKey.

Implements java.util.Map.containsKey.

Tests whether the specified object reference is a key in this identity hash map.

private boolean

Returns:

true if and only if the specified key-value mapping is in the map
containsMapping
(Object
possible key
key
,
Object
possible value
value
)

Tests if the specified key-value mapping is in the map.

public boolean

Returns:

true if this map maps one or more keys to the specified object reference
containsValue
(Object
value whose presence in this map is to be tested
value
)

Overrides java.util.AbstractMap.containsValue.

Implements java.util.Map.containsValue.

Tests whether the specified object reference is a value in this identity hash map.

public Set<Map.Entry<K, V>>

Returns:

a set view of the identity-mappings contained in this map
entrySet
()

Implements abstract java.util.AbstractMap.entrySet.

Implements java.util.Map.entrySet.

Returns a Set view of the mappings contained in this map.

public boolean

Returns:

true if the specified object is equal to this map
equals
(Object
object to be compared for equality with this map
o
)

Overrides java.util.AbstractMap.equals.

Implements java.util.Map.equals.

Compares the specified object with this map for equality.

public void
forEach(BiConsumer<? super K, ? super V>
The action to be performed for each entry
action
)

Overrides default java.util.Map.forEach.

Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

public V
get(Object
the key whose associated value is to be returned
key
)

Overrides java.util.AbstractMap.get.

Implements java.util.Map.get.

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

private static int
hash(Object x, int length)

Returns index for Object x.

public int

Returns:

the hash code value for this map
hashCode
()

Overrides java.util.AbstractMap.hashCode.

Implements java.util.Map.hashCode.

Returns the hash code value for this map.

private void
init(int initCapacity)

Initializes object to be an empty map with the specified initial capacity, which is assumed to be a power of two between MINIMUM_CAPACITY and MAXIMUM_CAPACITY inclusive.

public boolean

Returns:

true if this identity hash map contains no key-value mappings
isEmpty
()

Overrides java.util.AbstractMap.isEmpty.

Implements java.util.Map.isEmpty.

Returns true if this identity hash map contains no key-value mappings.

public Set<K>

Returns:

an identity-based set view of the keys contained in this map
keySet
()

Overrides java.util.AbstractMap.keySet.

Implements java.util.Map.keySet.

Returns an identity-based set view of the keys contained in this map.

private static Object
maskNull(Object key)

Use NULL_KEY for key if it is null.

private static int
nextKeyIndex(int i, int len)

Circularly traverses table of size len.

public V

Returns:

the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
put
(K
the key with which the specified value is to be associated
key
,
V
the value to be associated with the specified key
value
)

Overrides java.util.AbstractMap.put.

Implements java.util.Map.put.

Associates the specified value with the specified key in this identity hash map.

public void
putAll(Map<? extends K, ? extends V>
mappings to be stored in this map
m
)

Overrides java.util.AbstractMap.putAll.

Implements java.util.Map.putAll.

Copies all of the mappings from the specified map to this map.

private void
putForCreate(K key, V value)

The put method for readObject.

private void
readObject(ObjectInputStream s)

Reconstitutes the IdentityHashMap instance from a stream (i.e., deserializes it).

public V

Returns:

the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
remove
(Object
key whose mapping is to be removed from the map
key
)

Overrides java.util.AbstractMap.remove.

Implements java.util.Map.remove.

Removes the mapping for this key from this map if present.

public boolean
remove(Object
key with which the specified value is associated
key
,
Object
value expected to be associated with the specified key
value
)

Overrides default java.util.Map.remove.

Removes the entry for the specified key only if it is currently mapped to the specified value (optional operation).

private boolean

Returns:

true if and only if the specified key-value mapping was in the map
removeMapping
(Object
possible key
key
,
Object
possible value
value
)

Removes the specified key-value mapping from the map if it is present.

public boolean
replace(K
key with which the specified value is associated
key
,
V
value expected to be associated with the specified key
oldValue
,
V
value to be associated with the specified key
newValue
)

Overrides default java.util.Map.replace.

Replaces the entry for the specified key only if currently mapped to the specified value (optional operation).

public void
replaceAll(BiFunction<? super K, ? super V, ? extends V>
the function to apply to each entry
function
)

Overrides default java.util.Map.replaceAll.

Replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception (optional operation).

private boolean

Returns:

whether a resize did in fact take place
resize
(int
the new capacity, must be a power of two.
newCapacity
)

Resizes the table if necessary to hold given capacity.

public int

Returns:

the number of key-value mappings in this map
size
()

Overrides java.util.AbstractMap.size.

Implements java.util.Map.size.

Returns the number of key-value mappings in this identity hash map.

pack-priv static final Object
unmaskNull(Object key)

Returns internal representation of null key back to caller as null.

public Collection<V>
values()

Overrides java.util.AbstractMap.values.

Implements java.util.Map.values.

Returns a Collection view of the values contained in this map.

private void
writeObject(ObjectOutputStream s)

Saves the state of the IdentityHashMap instance to a stream (i.e., serializes it).

Inherited from java.util.AbstractMap:
toString