⇒ Index (Frames) |  ⇒ Index (No Frames) |  ⇒ Package |  ⇒ Package Tree |  ⇒ Full Tree 
org.apache.commons.collections.map

Class AbstractHashedMap

java.lang.Object
|
+--org.apache.commons.collections.map.AbstractHashedMap

All Implemented Interfaces:
IterableMap

Known Direct Subclasses:
AbstractLinkedMap, CaseInsensitiveMap, HashedMap, IdentityMap


public class AbstractHashedMap
extends java.lang.Object
implements IterableMap

An abstract implementation of a hash-based map which provides numerous points for subclasses to override.

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.

Since:
Commons Collections 3.0
Authors:
java util HashMap
Stephen Colebourne

Field Summary

transient AbstractHashedMap.HashEntry[]

data

Map entries

static int

DEFAULT_CAPACITY

The default capacity to use

static float

DEFAULT_LOAD_FACTOR

The default load factor to use

static int

DEFAULT_THRESHOLD

The default threshold to use

transient AbstractHashedMap.EntrySet

entrySet

Entry set

static String

GETKEY_INVALID

static String

GETVALUE_INVALID

transient AbstractHashedMap.KeySet

keySet

Key set

transient float

loadFactor

Load factor, normally 0.75

static int

MAXIMUM_CAPACITY

The maximum capacity allowed

transient int

modCount

Modification count for iterators

static String

NO_NEXT_ENTRY

An abstract implementation of a hash-based map which provides numerous points for subclasses to override.

static String

NO_PREVIOUS_ENTRY

static Object

NULL

An object for masking null

static String

REMOVE_INVALID

static String

SETVALUE_INVALID

transient int

size

The size of the map

transient int

threshold

Size at which to rehash

transient AbstractHashedMap.Values

values

Values

Constructor Summary

AbstractHashedMap()

Constructor only used in deserialization, do not use otherwise.

AbstractHashedMap(int initialCapacity, float loadFactor, int threshold)

Constructor which performs no validation on the passed in parameters.

AbstractHashedMap(int initialCapacity)

Constructs a new, empty map with the specified initial capacity and default load factor.

AbstractHashedMap(int initialCapacity, float loadFactor)

Constructs a new, empty map with the specified initial capacity and load factor.

AbstractHashedMap(Map map)

Constructor copying elements from another map.

Method Summary

void

addEntry(AbstractHashedMap.HashEntry entry, int hashIndex)

Adds an entry into this map.

void

addMapping(int hashIndex, int hashCode, Object key, Object value)

Adds a new key-value mapping into this map.

int

calculateNewCapacity(int proposedCapacity)

Calculates the new capacity of the map.

int

calculateThreshold(int newCapacity, float factor)

Calculates the new threshold of the map, where it will be resized.

void

checkCapacity()

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.

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.

Object

convertKey(Object key)

Converts input keys to another object for storage in the map.

AbstractHashedMap.HashEntry

createEntry(AbstractHashedMap.HashEntry next, int hashCode, Object key, Object value)

Creates an entry to store the key-value data.

Iterator

createEntrySetIterator()

Creates an entry set iterator.

Iterator

createKeySetIterator()

Creates a key set iterator.

Iterator

createValuesIterator()

Creates a values iterator.

void

destroyEntry(AbstractHashedMap.HashEntry entry)

Kills an entry ready for the garbage collector.

void

doReadObject(ObjectInputStream in)

Reads the map data from the stream.

void

doWriteObject(ObjectOutputStream out)

Writes the map data to the stream.

void

ensureCapacity(int newCapacity)

Changes the size of the data structure to the capacity proposed.

Set

entrySet()

Gets the entrySet view of the map.

boolean

equals(Object obj)

Compares this map with another.

Object

get(Object key)

Gets the value mapped to the key specified.

AbstractHashedMap.HashEntry

getEntry(Object key)

Gets the entry mapped to the key specified.

int

hash(Object key)

Gets the hash code for the key specified.

int

hashCode()

Gets the standard Map hashCode.

int

hashIndex(int hashCode, int dataSize)

Gets the index into the data storage for the hashCode specified.

void

init()

Initialise subclasses during construction, cloning or deserialization.

boolean

isEmpty()

Checks whether the map is currently empty.

boolean

isEqualKey(Object key1, Object key2)

Compares two keys for equals.

boolean

isEqualValue(Object value1, Object value2)

Compares two values for equals.

Set

keySet()

Gets the keySet view of the map.

MapIterator

mapIterator()

Gets an iterator over the map.

Object

put(Object key, Object value)

Puts a key-value mapping into this map.

void

putAll(Map map)

Puts all the values from the specified map into this map.

Object

remove(Object key)

Removes the specified mapping from this map.

void

removeEntry(AbstractHashedMap.HashEntry entry, int hashIndex, AbstractHashedMap.HashEntry previous)

Removes an entry from the chain stored in a particular index.

void

removeMapping(AbstractHashedMap.HashEntry entry, int hashIndex, AbstractHashedMap.HashEntry previous)

Removes a mapping from the map.

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.

String

toString()

Gets the map as a String.

void

updateEntry(AbstractHashedMap.HashEntry entry, Object newValue)

Updates an existing key-value mapping to change the value.

Collection

values()

Gets the values view of the map.

Field Details

data

protected transient AbstractHashedMap.HashEntry[] data

Map entries


DEFAULT_CAPACITY

protected static final int DEFAULT_CAPACITY

The default capacity to use


DEFAULT_LOAD_FACTOR

protected static final float DEFAULT_LOAD_FACTOR

The default load factor to use


DEFAULT_THRESHOLD

protected static final int DEFAULT_THRESHOLD

The default threshold to use


entrySet

protected transient AbstractHashedMap.EntrySet entrySet

Entry set


GETKEY_INVALID

protected static final String GETKEY_INVALID


GETVALUE_INVALID

protected static final String GETVALUE_INVALID


keySet

protected transient AbstractHashedMap.KeySet keySet

Key set


loadFactor

protected transient float loadFactor

Load factor, normally 0.75


MAXIMUM_CAPACITY

protected static final int MAXIMUM_CAPACITY

The maximum capacity allowed


modCount

protected transient int modCount

Modification count for iterators


NO_NEXT_ENTRY

protected static final String NO_NEXT_ENTRY

An abstract implementation of a hash-based map which provides numerous points for subclasses to override.

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.

Since:
Commons Collections 3.0
Authors:
java util HashMap
Stephen Colebourne

NO_PREVIOUS_ENTRY

protected static final String NO_PREVIOUS_ENTRY


NULL

protected static final Object NULL

An object for masking null


REMOVE_INVALID

protected static final String REMOVE_INVALID


SETVALUE_INVALID

protected static final String SETVALUE_INVALID


size

protected transient int size

The size of the map


threshold

protected transient int threshold

Size at which to rehash


values

protected transient AbstractHashedMap.Values 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 two
loadFactor - the load factor, must be > 0.0f and generally < 1.0f
threshold - the threshold, must be sensible

AbstractHashedMap

protected AbstractHashedMap(int initialCapacity, float loadFactor)

Constructs a new, empty map with the specified initial capacity and load factor.

Parameters:
initialCapacity - the initial capacity
loadFactor - the load factor
Throws:
- if the initial capacity is less than one
- if the load factor is less than or equal to zero

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:
- if the initial capacity is less than one

AbstractHashedMap

protected AbstractHashedMap(Map map)

Constructor copying elements from another map.

Parameters:
map - the map to copy
Throws:
- if the map is null

Method Details

addEntry

protected void addEntry(AbstractHashedMap.HashEntry entry, int hashIndex)

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 add
hashIndex - the index into the data array to store at

addMapping

protected void addMapping(int hashIndex, int hashCode, Object key, Object value)

Adds a new key-value mapping into this map.

This implementation calls createEntry(), addEntry() and checkCapacity(). It also handles changes to modCount and size. Subclasses could override to fully control adds to the map.

Parameters:
hashIndex - the index into the data array to store at
hashCode - the hash code of the key to add
key - the key to add
value - the value to add

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 capacity
factor - the load factor
Returns:
the new resize threshold

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


clear

public void clear()

Clears the map, resetting the size to zero and nullifying references to avoid garbage collection issues.


clone

protected Object clone()

Clones the map without cloning the keys or values.

To implement clone(), a subclass must implement the Cloneable interface and make this method public.

Returns:
a shallow clone

containsKey

public boolean containsKey(Object key)

Checks whether the map contains the specified key.

Parameters:
key - the key to search for
Returns:
true if the map contains the key

containsValue

public boolean containsValue(Object value)

Checks whether the map contains the specified value.

Parameters:
value - the value to search for
Returns:
true if the map contains the value

convertKey

protected Object convertKey(Object key)

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

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 sequence
hashCode - the hash code to use
key - the key to store
value - the value to store
Returns:
the newly created entry

createEntrySetIterator

protected Iterator createEntrySetIterator()

Creates an entry set iterator. Subclasses can override this to return iterators with different properties.

Returns:
the entrySet iterator

createKeySetIterator

protected Iterator createKeySetIterator()

Creates a key set iterator. Subclasses can override this to return iterators with different properties.

Returns:
the keySet iterator

createValuesIterator

protected Iterator createValuesIterator()

Creates a values iterator. Subclasses can override this to return iterators with different properties.

Returns:
the values iterator

destroyEntry

protected void destroyEntry(AbstractHashedMap.HashEntry entry)

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

doReadObject

protected void doReadObject(ObjectInputStream in)

Reads the map data from the stream. This method must be overridden if a subclass must be setup before put() 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() or calculateThreshold() will work correctly.

Parameters:
in - the input stream

doWriteObject

protected void doWriteObject(ObjectOutputStream out)

Writes the map data to the stream. This method must be overridden if a subclass must be setup before put() 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:
out - the output stream

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

entrySet

public Set entrySet()

Returns:
the entrySet view

equals

public boolean equals(Object obj)

Compares this map with another.

Parameters:
obj - the object to compare to
Returns:
true if equal

get

public Object get(Object key)

Gets the value mapped to the key specified.

Parameters:
key - the key
Returns:
the mapped value, null if no match

getEntry

protected AbstractHashedMap.HashEntry getEntry(Object key)

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

hash

protected int hash(Object key)

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

hashCode

public int hashCode()

Gets the standard Map hashCode.

Returns:
the hash code defined in the Map interface

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 use
dataSize - the size of the data to pick a bucket from
Returns:
the bucket index

init

protected void init()

Initialise subclasses during construction, cloning or deserialization.


isEmpty

public boolean isEmpty()

Checks whether the map is currently empty.

Returns:
true if the map is currently size zero

isEqualKey

protected boolean isEqualKey(Object key1, Object key2)

Compares two keys for equals. This implementation uses the equals method. Subclasses can override this to match differently.

Parameters:
key1 - the first key to compare
key2 - the second key to compare
Returns:
true if equal

isEqualValue

protected boolean isEqualValue(Object value1, Object value2)

Compares two values for equals. This implementation uses the equals method. Subclasses can override this to match differently.

Parameters:
value1 - the first value to compare
value2 - the second value to compare
Returns:
true if equal

keySet

public Set keySet()

Returns:
the keySet view

mapIterator

public MapIterator 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.

Returns:
the map iterator

put

public Object put(Object key, Object value)

Puts a key-value mapping into this map.

Parameters:
key - the key to add
value - the value to add
Returns:
the value previously mapped to this key, null if none

putAll

public void putAll(Map map)

Puts all the values from the specified map into this map.

Parameters:
map - the map to add
Throws:
- if the map is null

remove

public Object remove(Object key)

Removes the specified mapping from this map.

Parameters:
key - the mapping to remove
Returns:
the value mapped to the removed key, null if key not in map

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 remove
hashIndex - the index into the data structure
previous - the previous entry in the chain

removeMapping

protected void removeMapping(AbstractHashedMap.HashEntry entry, int hashIndex, AbstractHashedMap.HashEntry previous)

Removes a mapping from the map.

This implementation calls removeEntry() and destroyEntry(). It also handles changes to modCount and size. Subclasses could override to fully control removals from the map.

Parameters:
entry - the entry to remove
hashIndex - the index into the data structure
previous - the previous entry in the chain

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 null
hashIndex - the index in the data array
hashCode - the hash code of the key to add
key - the key to add
value - the value to add

size

public int size()

Gets the size of the map.

Returns:
the size

toString

public String toString()

Gets the map as a String.

Returns:
a string version of the map

updateEntry

protected void updateEntry(AbstractHashedMap.HashEntry entry, Object newValue)

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 update
newValue - the new value to store

values

public Collection values()

Returns:
the values view