Wednesday, June 27, 2012

How HashMap works in Java

A collection allows key+value pair and
HashMap accept null while Hashtable doesn't.
HashMap is not synchronized, hashMap is fast, etc.,
Hashtable 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.

Do you Know how HashMap works in Java
or
How does get () method of HashMap works in Java

HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from HashMap. When we pass an object to put () method to store it on HashMap, it's implementation calls hashcode() method by applying that hashcode on its own hashing funtion it identifies a bucket location for storing key+value pair, important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic.

What will happen if two different objects have same hashcode?

Remember, equals and hashCode() contract that two unequal object in Java very much can have equal hashcode.
"Since hashcode () is same, bucket location would be same and collision occurs in hashMap,
Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list.
How will you retrieve if two different objects have same hashcode?

get() method uses keys hashcode to find bucket location and retrieves value object.
In the case of collision that there are two objects are stored in same bucket, by traversal in linked list until it will find the value object.

















 Collision resolution -

1. Chaining :

Hash collision resolved by chaining.





2. Open addressing :

Hash collision resolved by linear probing (interval=1).

Hashtable
HashMap
Introduced with JDK 1.0 version, the starting version of Java
Introduced with JDK 1.2
Part of legacy classes (the data structures of JDK 1.0 are known as legacy classes)
Methods of Hashtable are synchronized by default
Methods are not synchronized by default
Does not permit null values (trying to add, throwsNullPointerException)
Permits null values (either key or value)
Enumeration interface is used for iterating keys
Iterator is used for iterating the keys
Enumerator is not fail-fast
Iterator is fail-fast
Safe for multithreaded applications
Better for non-threaded applications
Low performance due to synchronization
High performance
Hashtable is serialized
HashMap is not serialized



No comments: