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).
|
No comments:
Post a Comment