|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object java.util.AbstractMap java.util.IdentityHashMap
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.
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 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 this 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 HashMap(...));
The iterators 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 or add methods, 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.
Implementation note: This is a simple linear-probe hash table,
as described for example in texts by Sedgewick and Knuth. The array
alternates holding keys and values. (This has better locality for large
tables than does using separate arrays.) For many JRE implementations
and operation mixes, this class will yield better performance than
HashMap
(which uses chaining rather than linear-probing).
This class is a member of the Java Collections Framework.
System.identityHashCode(Object)
,
Object.hashCode()
,
Collection
,
Map
,
HashMap
,
TreeMap
,
Serialized FormNested Class Summary | |
private class |
IdentityHashMap.EntryIterator
Since we don't use Entry objects, we use the Iterator itself as an entry. |
private class |
IdentityHashMap.EntrySet
|
private class |
IdentityHashMap.IdentityHashMapIterator
|
private class |
IdentityHashMap.KeyIterator
|
private class |
IdentityHashMap.KeySet
|
private class |
IdentityHashMap.ValueIterator
|
private class |
IdentityHashMap.Values
|
Nested classes inherited from class java.util.AbstractMap |
AbstractMap.SimpleEntry |
Nested classes inherited from class java.util.Map |
Map.Entry |
Field Summary | |
private static int |
DEFAULT_CAPACITY
The initial capacity used by the no-args constructor. |
private Set |
entrySet
This field is initialized to contain an instance of the entry set view the first time this view is requested. |
private static int |
MAXIMUM_CAPACITY
The maximum capacity, used if a higher value is implicitly specified by either of the constructors with arguments. |
private static int |
MINIMUM_CAPACITY
The minimum capacity, used if a lower value is implicitly specified by either of the constructors with arguments. |
private int |
modCount
The number of modifications, to support fast-fail iterators |
private static Object |
NULL_KEY
Value representing null keys inside tables. |
private int |
size
The number of key-value mappings contained in this identity hash map. |
private Object[] |
table
The table, resized as necessary. |
private int |
threshold
The next size value at which to resize (capacity * load factor). |
Fields inherited from class java.util.AbstractMap |
keySet, values |
Constructor Summary | |
IdentityHashMap()
Constructs 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 m)
Constructs a new identity hash map containing the keys-value mappings in the specified map. |
Method Summary | |
private int |
capacity(int expectedMaxSize)
Returns the appropriate capacity for the specified expected maximum size. |
void |
clear()
Removes all mappings from this map. |
Object |
clone()
Returns a shallow copy of this identity hash map: the keys and values themselves are not cloned. |
private void |
closeDeletion(int d)
Rehash all possibly-colliding entries following a deletion. |
boolean |
containsKey(Object key)
Tests whether the specified object reference is a key in this identity hash map. |
private boolean |
containsMapping(Object key,
Object value)
Tests if the specified key-value mapping is in the map. |
boolean |
containsValue(Object value)
Tests whether the specified object reference is a value in this identity hash map. |
Set |
entrySet()
Returns a set view of the mappings contained in this map. |
boolean |
equals(Object o)
Compares the specified object with this map for equality. |
Object |
get(Object key)
Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapping for this key. |
private static int |
hash(Object x,
int length)
Return index for Object x. |
int |
hashCode()
Returns the hash code value for this map. |
private void |
init(int initCapacity)
Initialize 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. |
boolean |
isEmpty()
Returns true if this identity hash map contains no key-value mappings. |
Set |
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 traverse table of size len. |
Object |
put(Object key,
Object value)
Associates the specified value with the specified key in this identity hash map. |
void |
putAll(Map t)
Copies all of the mappings from the specified map to this map These mappings will replace any mappings that this map had for any of the keys currently in the specified map. |
private void |
readObject(ObjectInputStream s)
Reconstitute the IdentityHashMap instance from a stream (i.e., deserialize it). |
Object |
remove(Object key)
Removes the mapping for this key from this map if present. |
private boolean |
removeMapping(Object key,
Object value)
Removes the specified key-value mapping from the map if it is present. |
private void |
resize(int newCapacity)
Resize the table to hold given capacity. |
int |
size()
Returns the number of key-value mappings in this identity hash map. |
private static Object |
unmaskNull(Object key)
Return internal representation of null key back to caller as null |
Collection |
values()
Returns a collection view of the values contained in this map. |
private void |
writeObject(ObjectOutputStream s)
Save the state of the IdentityHashMap instance to a stream (i.e., serialize it). |
Methods inherited from class java.util.AbstractMap |
toString |
Methods inherited from class java.lang.Object |
finalize, getClass, notify, notifyAll, wait, wait, wait |
Field Detail |
private static final int DEFAULT_CAPACITY
private static final int MINIMUM_CAPACITY
private static final int MAXIMUM_CAPACITY
private transient Object[] table
private int size
private transient volatile int modCount
private transient int threshold
private static final Object NULL_KEY
private transient Set entrySet
Constructor Detail |
public IdentityHashMap()
public IdentityHashMap(int expectedMaxSize)
expectedMaxSize
- the expected maximum size of the map.
IllegalArgumentException
- if expectedMaxSize is negativepublic IdentityHashMap(Map m)
m
- the map whose mappings are to be placed into this map.
NullPointerException
- if the specified map is null.Method Detail |
private static Object maskNull(Object key)
private static Object unmaskNull(Object key)
private int capacity(int expectedMaxSize)
private void init(int initCapacity)
public int size()
size
in interface Map
size
in class AbstractMap
public boolean isEmpty()
isEmpty
in interface Map
isEmpty
in class AbstractMap
private static int hash(Object x, int length)
private static int nextKeyIndex(int i, int len)
public Object get(Object key)
get
in interface Map
get
in class AbstractMap
key
- the key whose associated value is to be returned.
put(Object, Object)
public boolean containsKey(Object key)
containsKey
in interface Map
containsKey
in class AbstractMap
key
- possible key.
true
if the specified object reference is a key
in this map.containsValue(Object)
public boolean containsValue(Object value)
containsValue
in interface Map
containsValue
in class AbstractMap
value
- value whose presence in this map is to be tested.
containsKey(Object)
private boolean containsMapping(Object key, Object value)
key
- possible key.value
- possible value.
true
if and only if the specified key-value
mapping is in map.public Object put(Object key, Object value)
put
in interface Map
put
in class AbstractMap
key
- the key with which the specified value is to be associated.value
- the value to be associated with the specified key.
Object.equals(Object)
,
get(Object)
,
containsKey(Object)
private void resize(int newCapacity)
newCapacity
- the new capacity, must be a power of two.public void putAll(Map t)
putAll
in interface Map
putAll
in class AbstractMap
t
- mappings to be stored in this map.
NullPointerException
- if the specified map is null.public Object remove(Object key)
remove
in interface Map
remove
in class AbstractMap
key
- key whose mapping is to be removed from the map.
private boolean removeMapping(Object key, Object value)
key
- possible key.value
- possible value.
true
if and only if the specified key-value
mapping was in map.private void closeDeletion(int d)
d
- the index of a newly empty deleted slotpublic void clear()
clear
in interface Map
clear
in class AbstractMap
public boolean equals(Object o)
Owing to the reference-equality-based semantics of this map it is possible that the symmetry and transitivity requirements of the Object.equals contract may be violated if this map is compared to a normal map. However, the Object.equals contract is guaranteed to hold among IdentityHashMap instances.
equals
in interface Map
equals
in class AbstractMap
o
- object to be compared for equality with this map.
Object.equals(Object)
public int hashCode()
Object.hashCode()
.
Owing to the reference-equality-based semantics of the Map.Entry instances in the set returned by this map's entrySet method, it is possible that the contractual requirement of Object.hashCode mentioned in the previous paragraph will be violated if one of the two objects being compared is an IdentityHashMap instance and the other is a normal map.
hashCode
in interface Map
hashCode
in class AbstractMap
Object.hashCode()
,
Object.equals(Object)
,
equals(Object)
public Object clone()
clone
in class AbstractMap
public Set keySet()
While the object returned by this method implements the Set interface, it does not obey Set's general 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 its contains, remove, containsAll, equals, and hashCode methods.
The equals method of the returned set returns true only if the specified object is a set containing exactly the same object references as the returned set. The symmetry and transitivity requirements of the Object.equals contract may be violated if the set returned by this method is compared to a normal set. However, the Object.equals contract is guaranteed to hold among sets returned by this method.
The hashCode method 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 the equals method, in order to enforce the general contract of the Object.hashCode method among sets returned by this method.
keySet
in interface Map
keySet
in class AbstractMap
Object.equals(Object)
,
System.identityHashCode(Object)
public Collection values()
Returns a collection view 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 the Iterator.remove, Collection.remove, removeAll, retainAll and clear methods. It does not support the add or addAll methods.
While the object returned by this method implements the Collection interface, it does not obey Collection's general 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 its contains, remove and containsAll methods.
values
in interface Map
values
in class AbstractMap
public Set entrySet()
Like the backing map, the Map.Entry objects in the set returned by this method define key and value equality as reference-equality rather than object-equality. This affects the behavior of the equals and hashCode methods of these Map.Entry objects. A reference-equality based Map.Entry e is equal to an object o if and only if o is a Map.Entry and e.getKey()==o.getKey() && e.getValue()==o.getValue(). To accommodate these equals semantics, the hashCode method returns System.identityHashCode(e.getKey()) ^ System.identityHashCode(e.getValue()).
Owing to the reference-equality-based semantics of the
Map.Entry instances in the set returned by this method,
it is possible that the symmetry and transitivity requirements of
the Object.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, the Object.equals contract is guaranteed to
hold among identity-based map entries, and among sets of such entries.
entrySet
in interface Map
entrySet
in class AbstractMap
private void writeObject(ObjectOutputStream s) throws IOException
IOException
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException
IOException
ClassNotFoundException
|
||||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |