Class AbstractHashedMap
- All Implemented Interfaces:
IterableMap
,Map
- Direct Known Subclasses:
AbstractReferenceMap
This class implements all the features necessary for a subclass hash-based map.
Key-value entries are stored in instances of the HashEntry
class,
which can be overridden and replaced. The iterators can similarly be replaced,
without the need to replace the KeySet, EntrySet and Values view classes.
Overridable methods are provided to change the default hashing behaviour, and to change how entries are added to and removed from the map. Hopefully, all you need for unusual subclasses is here.
NOTE: From Commons Collections 3.1 this class extends AbstractMap. This is to provide backwards compatibility for ReferenceMap between v3.0 and v3.1. This extends clause will be removed in v4.0.
- Since:
- Commons Collections 3.0
- Version:
- $Revision$ $Date$
- Author:
- java util HashMap, Stephen Colebourne, Christian Siefkes
-
Nested Class Summary
Modifier and TypeClassDescriptionprotected static class
EntrySet implementation.protected static class
EntrySet iterator.protected static class
HashEntry used to store the data.protected static class
Base Iteratorprotected static class
MapIterator implementation.protected static class
KeySet implementation.protected static class
KeySet iterator.protected static class
Values implementation.protected static class
Values iterator.Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K extends Object,
V extends Object>, AbstractMap.SimpleImmutableEntry<K extends Object, V extends Object> -
Field Summary
Modifier and TypeFieldDescriptionprotected AbstractHashedMap.HashEntry[]
Map entriesprotected static final int
The default capacity to useprotected static final float
The default load factor to useprotected static final int
The default threshold to useprotected AbstractHashedMap.EntrySet
Entry setprotected static final String
Message.protected static final String
Message.protected AbstractHashedMap.KeySet
Key setprotected float
Load factor, normally 0.75protected static final int
The maximum capacity allowedprotected int
Modification count for iteratorsprotected static final String
Message.protected static final String
Message.protected static final Object
An object for masking nullprotected static final String
Message.protected static final String
Message.protected int
The size of the mapprotected int
Size at which to rehashprotected AbstractHashedMap.Values
Values -
Constructor Summary
ModifierConstructorDescriptionprotected
Constructor only used in deserialization, do not use otherwise.protected
AbstractHashedMap
(int initialCapacity) Constructs a new, empty map with the specified initial capacity and default load factor.protected
AbstractHashedMap
(int initialCapacity, float loadFactor) Constructs a new, empty map with the specified initial capacity and load factor.protected
AbstractHashedMap
(int initialCapacity, float loadFactor, int threshold) Constructor which performs no validation on the passed in parameters.protected
AbstractHashedMap
(Map map) Constructor copying elements from another map. -
Method Summary
Modifier and TypeMethodDescriptionprotected void
addEntry
(AbstractHashedMap.HashEntry entry, int hashIndex) Adds an entry into this map.protected void
addMapping
(int hashIndex, int hashCode, Object key, Object value) Adds a new key-value mapping into this map.protected int
calculateNewCapacity
(int proposedCapacity) Calculates the new capacity of the map.protected int
calculateThreshold
(int newCapacity, float factor) Calculates the new threshold of the map, where it will be resized.protected void
Checks the capacity of the map and enlarges it if necessary.void
clear()
Clears the map, resetting the size to zero and nullifying references to avoid garbage collection issues.protected Object
clone()
Clones the map without cloning the keys or values.boolean
containsKey
(Object key) Checks whether the map contains the specified key.boolean
containsValue
(Object value) Checks whether the map contains the specified value.protected Object
convertKey
(Object key) Converts input keys to another object for storage in the map.protected AbstractHashedMap.HashEntry
createEntry
(AbstractHashedMap.HashEntry next, int hashCode, Object key, Object value) Creates an entry to store the key-value data.protected Iterator
Creates an entry set iterator.protected Iterator
Creates a key set iterator.protected Iterator
Creates a values iterator.protected void
Kills an entry ready for the garbage collector.protected void
doReadObject
(ObjectInputStream input) Reads the map data from the stream.protected void
doWriteObject
(ObjectOutputStream outStream) Writes the map data to the stream.protected void
ensureCapacity
(int newCapacity) Changes the size of the data structure to the capacity proposed.protected int
Gets thehashCode
field from aHashEntry
.protected Object
Gets thekey
field from aHashEntry
.protected AbstractHashedMap.HashEntry
Gets thenext
field from aHashEntry
.entrySet()
Gets the entrySet view of the map.protected Object
Gets thevalue
field from aHashEntry
.boolean
Compares this map with another.Gets the value mapped to the key specified.protected AbstractHashedMap.HashEntry
Gets the entry mapped to the key specified.protected int
Gets the hash code for the key specified.int
hashCode()
Gets the standard Map hashCode.protected int
hashIndex
(int hashCode, int dataSize) Gets the index into the data storage for the hashCode specified.protected void
init()
Initialise subclasses during construction, cloning or deserialization.boolean
isEmpty()
Checks whether the map is currently empty.protected boolean
isEqualKey
(Object key1, Object key2) Compares two keys, in internal converted form, to see if they are equal.protected boolean
isEqualValue
(Object value1, Object value2) Compares two values, in external form, to see if they are equal.keySet()
Gets the keySet view of the map.Gets an iterator over the map.Puts a key-value mapping into this map.void
Puts all the values from the specified map into this map.Removes the specified mapping from this map.protected void
removeEntry
(AbstractHashedMap.HashEntry entry, int hashIndex, AbstractHashedMap.HashEntry previous) Removes an entry from the chain stored in a particular index.protected void
removeMapping
(AbstractHashedMap.HashEntry entry, int hashIndex, AbstractHashedMap.HashEntry previous) Removes a mapping from the map.protected void
reuseEntry
(AbstractHashedMap.HashEntry entry, int hashIndex, int hashCode, Object key, Object value) Reuses an existing key-value mapping, storing completely new data.int
size()
Gets the size of the map.toString()
Gets the map as a String.protected void
updateEntry
(AbstractHashedMap.HashEntry entry, Object newValue) Updates an existing key-value mapping to change the value.values()
Gets the values view of the map.Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.util.Map
compute, computeIfAbsent, computeIfPresent, forEach, getOrDefault, merge, putIfAbsent, remove, replace, replace, replaceAll
-
Field Details
-
NO_NEXT_ENTRY
Message.- See Also:
-
NO_PREVIOUS_ENTRY
Message.- See Also:
-
REMOVE_INVALID
Message.- See Also:
-
GETKEY_INVALID
Message.- See Also:
-
GETVALUE_INVALID
Message.- See Also:
-
SETVALUE_INVALID
Message.- See Also:
-
DEFAULT_CAPACITY
protected static final int DEFAULT_CAPACITYThe default capacity to use- See Also:
-
DEFAULT_THRESHOLD
protected static final int DEFAULT_THRESHOLDThe default threshold to use- See Also:
-
DEFAULT_LOAD_FACTOR
protected static final float DEFAULT_LOAD_FACTORThe default load factor to use- See Also:
-
MAXIMUM_CAPACITY
protected static final int MAXIMUM_CAPACITYThe maximum capacity allowed- See Also:
-
NULL
An object for masking null -
loadFactor
protected transient float loadFactorLoad factor, normally 0.75 -
size
protected transient int sizeThe size of the map -
data
Map entries -
threshold
protected transient int thresholdSize at which to rehash -
modCount
protected transient int modCountModification count for iterators -
entrySet
Entry set -
keySet
Key set -
values
Values
-
-
Constructor Details
-
AbstractHashedMap
protected AbstractHashedMap()Constructor only used in deserialization, do not use otherwise. -
AbstractHashedMap
protected AbstractHashedMap(int initialCapacity, float loadFactor, int threshold) Constructor which performs no validation on the passed in parameters.- Parameters:
initialCapacity
- the initial capacity, must be a power of twoloadFactor
- the load factor, must be > 0.0f and generally < 1.0fthreshold
- the threshold, must be sensible
-
AbstractHashedMap
protected AbstractHashedMap(int initialCapacity) Constructs a new, empty map with the specified initial capacity and default load factor.- Parameters:
initialCapacity
- the initial capacity- Throws:
IllegalArgumentException
- if the initial capacity is less than one
-
AbstractHashedMap
protected AbstractHashedMap(int initialCapacity, float loadFactor) Constructs a new, empty map with the specified initial capacity and load factor.- Parameters:
initialCapacity
- the initial capacityloadFactor
- the load factor- Throws:
IllegalArgumentException
- if the initial capacity is less than one or if the load factor is less than or equal to zero
-
AbstractHashedMap
Constructor copying elements from another map.- Parameters:
map
- the map to copy- Throws:
NullPointerException
- if the map is null
-
-
Method Details
-
init
protected void init()Initialise subclasses during construction, cloning or deserialization. -
get
Gets the value mapped to the key specified.- Specified by:
get
in interfaceMap
- Overrides:
get
in classAbstractMap
- Parameters:
key
- the key- Returns:
- the mapped value, null if no match
-
size
public int size()Gets the size of the map.- Specified by:
size
in interfaceMap
- Overrides:
size
in classAbstractMap
- Returns:
- the size
-
isEmpty
public boolean isEmpty()Checks whether the map is currently empty.- Specified by:
isEmpty
in interfaceMap
- Overrides:
isEmpty
in classAbstractMap
- Returns:
- true if the map is currently size zero
-
containsKey
Checks whether the map contains the specified key.- Specified by:
containsKey
in interfaceMap
- Overrides:
containsKey
in classAbstractMap
- Parameters:
key
- the key to search for- Returns:
- true if the map contains the key
-
containsValue
Checks whether the map contains the specified value.- Specified by:
containsValue
in interfaceMap
- Overrides:
containsValue
in classAbstractMap
- Parameters:
value
- the value to search for- Returns:
- true if the map contains the value
-
put
Puts a key-value mapping into this map.- Specified by:
put
in interfaceMap
- Overrides:
put
in classAbstractMap
- Parameters:
key
- the key to addvalue
- the value to add- Returns:
- the value previously mapped to this key, null if none
-
putAll
Puts all the values from the specified map into this map.This implementation iterates around the specified map and uses
put(Object, Object)
.- Specified by:
putAll
in interfaceMap
- Overrides:
putAll
in classAbstractMap
- Parameters:
map
- the map to add- Throws:
NullPointerException
- if the map is null
-
remove
Removes the specified mapping from this map.- Specified by:
remove
in interfaceMap
- Overrides:
remove
in classAbstractMap
- Parameters:
key
- the mapping to remove- Returns:
- the value mapped to the removed key, null if key not in map
-
clear
public void clear()Clears the map, resetting the size to zero and nullifying references to avoid garbage collection issues.- Specified by:
clear
in interfaceMap
- Overrides:
clear
in classAbstractMap
-
convertKey
Converts input keys to another object for storage in the map. This implementation masks nulls. Subclasses can override this to perform alternate key conversions.The reverse conversion can be changed, if required, by overriding the getKey() method in the hash entry.
- Parameters:
key
- the key convert- Returns:
- the converted key
-
hash
Gets the hash code for the key specified. This implementation uses the additional hashing routine from JDK1.4. Subclasses can override this to return alternate hash codes.- Parameters:
key
- the key to get a hash code for- Returns:
- the hash code
-
isEqualKey
Compares two keys, in internal converted form, to see if they are equal. This implementation uses the equals method and assumes neither key is null. Subclasses can override this to match differently.- Parameters:
key1
- the first key to compare passed in from outsidekey2
- the second key extracted from the entry viaentry.key
- Returns:
- true if equal
-
isEqualValue
Compares two values, in external form, to see if they are equal. This implementation uses the equals method and assumes neither value is null. Subclasses can override this to match differently.- Parameters:
value1
- the first value to compare passed in from outsidevalue2
- the second value extracted from the entry viagetValue()
- Returns:
- true if equal
-
hashIndex
protected int hashIndex(int hashCode, int dataSize) Gets the index into the data storage for the hashCode specified. This implementation uses the least significant bits of the hashCode. Subclasses can override this to return alternate bucketing.- Parameters:
hashCode
- the hash code to usedataSize
- the size of the data to pick a bucket from- Returns:
- the bucket index
-
getEntry
Gets the entry mapped to the key specified.This method exists for subclasses that may need to perform a multi-step process accessing the entry. The public methods in this class don't use this method to gain a small performance boost.
- Parameters:
key
- the key- Returns:
- the entry, null if no match
-
updateEntry
Updates an existing key-value mapping to change the value.This implementation calls
setValue()
on the entry. Subclasses could override to handle changes to the map.- Parameters:
entry
- the entry to updatenewValue
- the new value to store
-
reuseEntry
protected void reuseEntry(AbstractHashedMap.HashEntry entry, int hashIndex, int hashCode, Object key, Object value) Reuses an existing key-value mapping, storing completely new data.This implementation sets all the data fields on the entry. Subclasses could populate additional entry fields.
- Parameters:
entry
- the entry to update, not nullhashIndex
- the index in the data arrayhashCode
- the hash code of the key to addkey
- the key to addvalue
- the value to add
-
addMapping
Adds a new key-value mapping into this map.This implementation calls
createEntry()
,addEntry()
andcheckCapacity()
. It also handles changes tomodCount
andsize
. Subclasses could override to fully control adds to the map.- Parameters:
hashIndex
- the index into the data array to store athashCode
- the hash code of the key to addkey
- the key to addvalue
- the value to add
-
createEntry
protected AbstractHashedMap.HashEntry createEntry(AbstractHashedMap.HashEntry next, int hashCode, Object key, Object value) Creates an entry to store the key-value data.This implementation creates a new HashEntry instance. Subclasses can override this to return a different storage class, or implement caching.
- Parameters:
next
- the next entry in sequencehashCode
- the hash code to usekey
- the key to storevalue
- the value to store- Returns:
- the newly created entry
-
addEntry
Adds an entry into this map.This implementation adds the entry to the data storage table. Subclasses could override to handle changes to the map.
- Parameters:
entry
- the entry to addhashIndex
- the index into the data array to store at
-
removeMapping
protected void removeMapping(AbstractHashedMap.HashEntry entry, int hashIndex, AbstractHashedMap.HashEntry previous) Removes a mapping from the map.This implementation calls
removeEntry()
anddestroyEntry()
. It also handles changes tomodCount
andsize
. Subclasses could override to fully control removals from the map.- Parameters:
entry
- the entry to removehashIndex
- the index into the data structureprevious
- the previous entry in the chain
-
removeEntry
protected void removeEntry(AbstractHashedMap.HashEntry entry, int hashIndex, AbstractHashedMap.HashEntry previous) Removes an entry from the chain stored in a particular index.This implementation removes the entry from the data storage table. The size is not updated. Subclasses could override to handle changes to the map.
- Parameters:
entry
- the entry to removehashIndex
- the index into the data structureprevious
- the previous entry in the chain
-
destroyEntry
Kills an entry ready for the garbage collector.This implementation prepares the HashEntry for garbage collection. Subclasses can override this to implement caching (override clear as well).
- Parameters:
entry
- the entry to destroy
-
checkCapacity
protected void checkCapacity()Checks the capacity of the map and enlarges it if necessary.This implementation uses the threshold to check if the map needs enlarging
-
ensureCapacity
protected void ensureCapacity(int newCapacity) Changes the size of the data structure to the capacity proposed.- Parameters:
newCapacity
- the new capacity of the array (a power of two, less or equal to max)
-
calculateNewCapacity
protected int calculateNewCapacity(int proposedCapacity) Calculates the new capacity of the map. This implementation normalizes the capacity to a power of two.- Parameters:
proposedCapacity
- the proposed capacity- Returns:
- the normalized new capacity
-
calculateThreshold
protected int calculateThreshold(int newCapacity, float factor) Calculates the new threshold of the map, where it will be resized. This implementation uses the load factor.- Parameters:
newCapacity
- the new capacityfactor
- the load factor- Returns:
- the new resize threshold
-
entryNext
Gets thenext
field from aHashEntry
. Used in subclasses that have no visibility of the field.- Parameters:
entry
- the entry to query, must not be null- Returns:
- the
next
field of the entry - Throws:
NullPointerException
- if the entry is null- Since:
- Commons Collections 3.1
-
entryHashCode
Gets thehashCode
field from aHashEntry
. Used in subclasses that have no visibility of the field.- Parameters:
entry
- the entry to query, must not be null- Returns:
- the
hashCode
field of the entry - Throws:
NullPointerException
- if the entry is null- Since:
- Commons Collections 3.1
-
entryKey
Gets thekey
field from aHashEntry
. Used in subclasses that have no visibility of the field.- Parameters:
entry
- the entry to query, must not be null- Returns:
- the
key
field of the entry - Throws:
NullPointerException
- if the entry is null- Since:
- Commons Collections 3.1
-
entryValue
Gets thevalue
field from aHashEntry
. Used in subclasses that have no visibility of the field.- Parameters:
entry
- the entry to query, must not be null- Returns:
- the
value
field of the entry - Throws:
NullPointerException
- if the entry is null- Since:
- Commons Collections 3.1
-
mapIterator
Gets an iterator over the map. Changes made to the iterator affect this map.A MapIterator returns the keys in the map. It also provides convenient methods to get the key and value, and set the value. It avoids the need to create an entrySet/keySet/values object. It also avoids creating the Map.Entry object.
- Specified by:
mapIterator
in interfaceIterableMap
- Returns:
- the map iterator
-
entrySet
Gets the entrySet view of the map. Changes made to the view affect this map. To simply iterate through the entries, usemapIterator()
.- Specified by:
entrySet
in interfaceMap
- Specified by:
entrySet
in classAbstractMap
- Returns:
- the entrySet view
-
createEntrySetIterator
Creates an entry set iterator. Subclasses can override this to return iterators with different properties.- Returns:
- the entrySet iterator
-
keySet
Gets the keySet view of the map. Changes made to the view affect this map. To simply iterate through the keys, usemapIterator()
.- Specified by:
keySet
in interfaceMap
- Overrides:
keySet
in classAbstractMap
- Returns:
- the keySet view
-
createKeySetIterator
Creates a key set iterator. Subclasses can override this to return iterators with different properties.- Returns:
- the keySet iterator
-
values
Gets the values view of the map. Changes made to the view affect this map. To simply iterate through the values, usemapIterator()
.- Specified by:
values
in interfaceMap
- Overrides:
values
in classAbstractMap
- Returns:
- the values view
-
createValuesIterator
Creates a values iterator. Subclasses can override this to return iterators with different properties.- Returns:
- the values iterator
-
doWriteObject
Writes the map data to the stream. This method must be overridden if a subclass must be setup beforeput()
is used.Serialization is not one of the JDK's nicest topics. Normal serialization will initialise the superclass before the subclass. Sometimes however, this isn't what you want, as in this case the
put()
method on read can be affected by subclass state.The solution adopted here is to serialize the state data of this class in this protected method. This method must be called by the
writeObject()
of the first serializable subclass.Subclasses may override if they have a specific field that must be present on read before this implementation will work. Generally, the read determines what must be serialized here, if anything.
- Parameters:
outStream
- the output stream- Throws:
IOException
- write error
-
doReadObject
Reads the map data from the stream. This method must be overridden if a subclass must be setup beforeput()
is used.Serialization is not one of the JDK's nicest topics. Normal serialization will initialise the superclass before the subclass. Sometimes however, this isn't what you want, as in this case the
put()
method on read can be affected by subclass state.The solution adopted here is to deserialize the state data of this class in this protected method. This method must be called by the
readObject()
of the first serializable subclass.Subclasses may override if the subclass has a specific field that must be present before
put()
orcalculateThreshold()
will work correctly.- Parameters:
input
- the input stream- Throws:
IOException
- io errorClassNotFoundException
- class not found
-
clone
Clones the map without cloning the keys or values.To implement
clone()
, a subclass must implement theCloneable
interface and make this method public.- Overrides:
clone
in classAbstractMap
- Returns:
- a shallow clone
- Throws:
CloneNotSupportedException
-
equals
Compares this map with another.- Specified by:
equals
in interfaceMap
- Overrides:
equals
in classAbstractMap
- Parameters:
obj
- the object to compare to- Returns:
- true if equal
-
hashCode
public int hashCode()Gets the standard Map hashCode.- Specified by:
hashCode
in interfaceMap
- Overrides:
hashCode
in classAbstractMap
- Returns:
- the hash code defined in the Map interface
-
toString
Gets the map as a String.- Overrides:
toString
in classAbstractMap
- Returns:
- a string version of the map
-