“Hash Map is a Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) 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.” … from Java API
After reading this definition, some question comes in my mind:
How hash map store data internally?
What happen when I try to store some new information in map?
How hash map find my data?
And when I tried to explore it, I find it more and more interesting.
HashMap has a static class named Entry which implements Map.Entry interface. The Entry class looks like:
static class Entry implements Map.Entry {
final Object key;
Object value;
final int hash;
Entry next;
Entry(int i, Object obj, Object obj1, Entry entry) {
value = obj1;
next = entry;
key = obj;
hash = i;
}
// Other methods
}
Every time we insert a
Array
Link List
This image shows how hashmap manage data. Here
Each index of array is a bucket
To identify the bucket for any
Bucket (index) =HashMap.indexFor (HashMap.hash(key.hashCode()), entryArray.length)
It means, two keys with different hashCode can fall under same bucket.
If a bucket is empty (table[i] is null) then the Entry object is simply inserted at ith position
table[i] = new Entry(hash, key, value, null)
If a bucket has some values, then the following algo is used:
Entry entry = table[i]
Table[i] = new Entry(hash,key,value,entry)
It means, the latest entry resides on the top of the bucket.
http://mkbansal.wordpress.com/2010/06/24/hashmap-how-it-works/

