- Type Parameters:
K- the type of keys maintained by this mapV- the type of mapped values
- All Implemented Interfaces:
Serializable,Cloneable,Map<K,V>
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.- Since:
- 1.4
- See Also:
-
Nested Class Summary
Nested classes/interfaces declared in class java.util.AbstractMap
AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K, V> -
Constructor Summary
ConstructorsConstructorDescriptionConstructs a new, empty identity hash map with a default expected maximum size (21).IdentityHashMap(int expectedMaxSize) Constructs a new, empty map with the specified expected maximum size.IdentityHashMap(Map<? extends K, ? extends V> m) Constructs a new identity hash map containing the keys-value mappings in the specified map. -
Method Summary
Modifier and TypeMethodDescriptionvoidclear()Removes all of the mappings from this map.clone()Returns a shallow copy of this identity hash map: the keys and values themselves are not cloned.booleancontainsKey(Object key) Tests whether the specified object reference is a key in this identity hash map.booleancontainsValue(Object value) Tests whether the specified object reference is a value in this identity hash map.entrySet()Returns aSetview of the mappings contained in this map.booleanCompares the specified object with this map for equality.Returns the value to which the specified key is mapped, ornullif this map contains no mapping for the key.inthashCode()Returns the hash code value for this map.booleanisEmpty()Returnstrueif this identity hash map contains no key-value mappings.keySet()Returns an identity-based set view of the keys contained in this map.Associates the specified value with the specified key in this identity hash map.voidCopies all of the mappings from the specified map to this map.Removes the mapping for this key from this map if present.booleanRemoves the entry for the specified key only if it is currently mapped to the specified value.booleanReplaces the entry for the specified key only if currently mapped to the specified value.intsize()Returns the number of key-value mappings in this identity hash map.values()Returns aCollectionview of the values contained in this map.Methods declared in class java.util.AbstractMap
toStringMethods declared in interface java.util.Map
compute, computeIfAbsent, computeIfPresent, forEach, getOrDefault, merge, putIfAbsent, replace, replaceAll
-
Constructor Details
-
IdentityHashMap
public IdentityHashMap()Constructs a new, empty identity hash map with a default expected maximum size (21). -
IdentityHashMap
public IdentityHashMap(int expectedMaxSize) Constructs a new, empty map with the specified expected maximum size. Putting more than the expected number of key-value mappings into the map may cause the internal data structure to grow, which may be somewhat time-consuming.- Parameters:
expectedMaxSize- the expected maximum size of the map- Throws:
IllegalArgumentException- ifexpectedMaxSizeis negative
-
IdentityHashMap
Constructs a new identity hash map containing the keys-value mappings in the specified map.- Parameters:
m- the map whose mappings are to be placed into this map- Throws:
NullPointerException- if the specified map is null
-
-
Method Details
-
size
public int size()Returns the number of key-value mappings in this identity hash map. -
isEmpty
public boolean isEmpty()Returnstrueif this identity hash map contains no key-value mappings. -
get
Returns the value to which the specified key is mapped, ornullif this map contains no mapping for the key.More formally, if this map contains a mapping from a key
kto a valuevsuch that(key == k), then this method returnsv; otherwise it returnsnull. (There can be at most one such mapping.)A return value of
nulldoes not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key tonull. ThecontainsKeyoperation may be used to distinguish these two cases. -
containsKey
Tests whether the specified object reference is a key in this identity hash map. Returnstrueif and only if this map contains a mapping with keyksuch that(key == k).- Specified by:
containsKeyin interfaceMap<K,V> - Overrides:
containsKeyin classAbstractMap<K,V> - Parameters:
key- possible key- Returns:
trueif the specified object reference is a key in this map- See Also:
-
containsValue
Tests whether the specified object reference is a value in this identity hash map. Returnstrueif and only if this map contains a mapping with valuevsuch that(value == v).- Specified by:
containsValuein interfaceMap<K,V> - Overrides:
containsValuein classAbstractMap<K,V> - Parameters:
value- value whose presence in this map is to be tested- Returns:
trueif this map maps one or more keys to the specified object reference- See Also:
-
put
Associates the specified value with the specified key in this identity hash map. If this map alreadycontainsa mapping for the key, the old value is replaced, otherwise, a new mapping is inserted into this map.- Specified by:
putin interfaceMap<K,V> - Overrides:
putin classAbstractMap<K,V> - Parameters:
key- the key with which the specified value is to be associatedvalue- the value to be associated with the specified key- Returns:
- the previous value associated with
key, ornullif there was no mapping forkey. (Anullreturn can also indicate that the map previously associatednullwithkey.) - See Also:
-
putAll
Copies all of the mappings from the specified map to this map. For each mapping in the specified map, if this map alreadycontainsa mapping for the key, its value is replaced with the value from the specified map; otherwise, a new mapping is inserted into this map.- Specified by:
putAllin interfaceMap<K,V> - Overrides:
putAllin classAbstractMap<K,V> - Parameters:
m- mappings to be stored in this map- Throws:
NullPointerException- if the specified map is null
-
remove
Removes the mapping for this key from this map if present. The mapping is removed if and only if the mapping has a keyksuch that (key == k).- Specified by:
removein interfaceMap<K,V> - Overrides:
removein classAbstractMap<K,V> - Parameters:
key- key whose mapping is to be removed from the map- Returns:
- the previous value associated with
key, ornullif there was no mapping forkey. (Anullreturn can also indicate that the map previously associatednullwithkey.)
-
clear
public void clear()Removes all of the mappings from this map. The map will be empty after this call returns. -
equals
Compares the specified object with this map for equality. Returnstrueif the given object is also a map and the two maps represent identical object-reference mappings. More formally, this map is equal to another mapmif and only ifthis.entrySet().equals(m.entrySet()). See theentrySetmethod for the specification of equality of this map's entries.Owing to the reference-equality-based semantics of this map it is possible that the symmetry and transitivity requirements of the
Object.equalscontract may be violated if this map is compared to a normal map. However, theObject.equalscontract is guaranteed to hold amongIdentityHashMapinstances. -
hashCode
public int hashCode()Returns the hash code value for this map. The hash code of a map is defined to be the sum of the hash codes of each entry of this map. See theentrySetmethod for a specification of the hash code of this map's entries.This specification ensures that
m1.equals(m2)implies thatm1.hashCode()==m2.hashCode()for any twoIdentityHashMapinstancesm1andm2, as required by the general contract ofObject.hashCode().Owing to the reference-equality-based semantics of the
Map.Entryinstances in the set returned by this map'sentrySetmethod, it is possible that the contractual requirement ofObject.hashCodementioned in the previous paragraph will be violated if one of the two objects being compared is anIdentityHashMapinstance and the other is a normal map. -
clone
Returns a shallow copy of this identity hash map: the keys and values themselves are not cloned.- Overrides:
clonein classAbstractMap<K,V> - Returns:
- a shallow copy of this map
- See Also:
-
keySet
Returns an identity-based set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress, the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via theIterator.remove,Set.remove,removeAll,retainAll, andclearmethods. It does not support theaddoraddAllmethods.While the object returned by this method implements the
Setinterface, it does not obeySet'sgeneral contract. Like its backing map, the set returned by this method defines element equality as reference-equality rather than object-equality. This affects the behavior of itscontains,remove,containsAll,equals, andhashCodemethods.The
equalsmethod of the returned set returnstrueonly if the specified object is a set containing exactly the same object references as the returned set. The symmetry and transitivity requirements of theObject.equalscontract may be violated if the set returned by this method is compared to a normal set. However, theObject.equalscontract is guaranteed to hold among sets returned by this method.The
hashCodemethod of the returned set returns the sum of the identity hashcodes of the elements in the set, rather than the sum of their hashcodes. This is mandated by the change in the semantics of theequalsmethod, in order to enforce the general contract of theObject.hashCodemethod among sets returned by this method. -
values
Returns aCollectionview of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress, the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via theIterator.remove,Collection.remove,removeAll,retainAllandclearmethods. It does not support theaddoraddAllmethods.While the object returned by this method implements the
Collectioninterface, it does not obeyCollection'sgeneral contract. Like its backing map, the collection returned by this method defines element equality as reference-equality rather than object-equality. This affects the behavior of itscontains,removeandcontainsAllmethods. -
entrySet
Returns aSetview of the mappings contained in this map. Each element in the returned set is a reference-equality-basedMap.Entry. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress, the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via theIterator.remove,Set.remove,removeAll,retainAllandclearmethods. It does not support theaddoraddAllmethods.Like the backing map, the
Map.Entryobjects in the set returned by this method define key and value equality as reference-equality rather than object-equality. This affects the behavior of theequalsandhashCodemethods of theseMap.Entryobjects. A reference-equality basedMap.Entry eis equal to an objectoif and only ifois aMap.Entryande.getKey()==o.getKey() && e.getValue()==o.getValue(). To accommodate these equals semantics, thehashCodemethod returnsSystem.identityHashCode(e.getKey()) ^ System.identityHashCode(e.getValue()). (While the keys and values are compared using reference equality, theMap.Entryobjects themselves are not.)Owing to the reference-equality-based semantics of the
Map.Entryinstances in the set returned by this method, it is possible that the symmetry and transitivity requirements of theObject.equals(Object)contract may be violated if any of the entries in the set is compared to a normal map entry, or if the set returned by this method is compared to a set of normal map entries (such as would be returned by a call to this method on a normal map). However, theObject.equalscontract is guaranteed to hold among identity-based map entries, and among sets of such entries. -
remove
Removes the entry for the specified key only if it is currently mapped to the specified value.More formally, if this map contains a mapping from a key
kto a valuevsuch that(key == k)and(value == v), then this method removes the mapping for this key and returnstrue; otherwise it returnsfalse. -
replace
Replaces the entry for the specified key only if currently mapped to the specified value.More formally, if this map contains a mapping from a key
kto a valuevsuch that(key == k)and(oldValue == v), then this method associateskwithnewValueand returnstrue; otherwise it returnsfalse.
-