Saturday, 6 December 2008

Basics of HashMap

HashMap is an unsynchronized hashtable which permits null values. It extends the AbstractMap class, which is a partial implementation of the Map interface.

Methods inherited from Map include:

Object get(Object key)
Object put(Object key, Object value)
void putAll(Map t) - copy all mappings from t
Object remove(Object key) - returns previously associated value or null

To access the collection of keys and values in a Map, the interface declares the following methods:

public Set keySet()
public Collection values()

To iterate through the keys of a HashMap you can do:

final Iterator mapIterator = map.keySet.iterator();
while (mapIterator.hasNext()) {
final String key = (String) mapIterator.next();
final CustomType value = (CustomType) map.get(key);
}

HashMap provides constant-time performance for its basic operations (get and put) i.e. RETRIEVAL and INSERTION, assuming the hash function distributes the elements properly among the buckets.

No comments:

Blog Archive