How does Java HashMap or linkedhahsmap handles collisions

Source: Internet
Author: User
Tags map class

prior to Java 8, HashMap and all other hashes table based MAP implementation classes in Ja VA handle collision by  chaining , i.e. they use linked List to store map entries which ended in the Same bucket due to a collision. If A key end up in same buckets location where an entry are already stored then this entry are just added at the head of the Linked list there. In the worst case this degrades the performance of The get () method of Hashmap to o (n)  from o (1). In order to address this issue in the case of frequent HashMap collisions, Java8 have started using a balanced tree Instea D of linked list for storing collided entries. This also means, the worst case, you'll get a performance boost from  O (n)  to  o (log n) .

The threshold of switching to the balanced tree are defined as Treeify_threshold constant in Java.util.HashMap JDK 8 Co  De. Currently, it's value is 8, which means if there be more than 8 elements in the same bucket than HashMap would use a tree Instead of linked list to hold them in the same bucket.  This is the continuation of efforts to improve most used classes. If you remember earlier in JDK 7 They has also introduced a change so that empty ArrayList and HashMap would take less mem Ory by postponing the allocation of the underlying array until a element is added.

This is a dynamic feature which means HASHMAP would initially use the linked list if the number of entries Crosse s a certain threshold it'll replace the linked list with a balanced binary tree. Also, this feature would not be available to all hash table based classes in Java e.g. Hashtable would not has this featur e because of its legacy nature and given, the feature can change the traditional legacy iteration order of Hasht Able. Similarly, Weakhashmap would also not include the This feature.

So far (until JDK 8) only Concurrenthashmap, Linkedhashmap and HashMap would use the balanced tree in case of a frequent Co Llision. This is a dynamic feature which means HASHMAP would initially use the linked list if the number of EN Tries crosses a certain threshold it'll replace the linked list with a balanced binary tree.


When does collision occur in HashMapThere is several class in JDK which is based upon the hash table data structure e.g.
HashMap,
Linkedhashmap,
Hashtable,
Weakhashmap,
Identityhashmap,
Concurrenthashmap,
TreeMap, and
Enummap.

Underlying working of all these Map are pretty much same as discussed in what does HASHMAP internally works in Java, except Some minor differences in their specific behaviors. Since Hash table data structure is subject to collision all these implementations be required to handle the collision.

A collision occurs when a hash function returns same buckets location for both different keys. Since all hashes based Map class e.g. HashMap uses Equals () and hashcode () contract to find the bucket. HashMap calls the Hashcode () method to compute the hash value which are used to find the bucket location as shown in below Code snippet from the HashMap class of JDK 1.7 (jkd1.7.0_60) update.

Ignoring the first and lines, which was the performance improvement do for String keys in JDK 7, you can see that comput Ation of Hash is totally based upon the Hashcode method.

A collision would occur when both different keys have the same hashcode, which can happen because the unequal objects in Jav A can has the same hashcode.



Summary1) HashMap handles collision by using the linked list toStoreMap entries ended up in the same array location or bucket location.

2) from Java 8 onwards, HASHMAP, Concurrenthashmap, and Linkedhashmap would use the balanced tree in place of linked list T O Handle frequently hash collisions. The idea was to switch to the balanced tree once the number of items in a hash bucket grows beyond a certain threshold. This would improve the worst case get () method performance from O (n) to O (log n).

3) by switching from linked list to balanced tree for handling collision, the iteration order of HashMap would change. This is Ok because HashMap doesn ' t provide all guarantee on iteration order and any code which depends upon it is Likel Y to break.

4) Legacy class Hashtable which exists in JDK from Java 1 won't use the balanced binary tree to handle frequent hash co Llision to keep its iteration order intact. This is decided to avoid breaking many legacy JavaApplicationWhich depends upon iteration order of Hashtable.

5) Apart from Hashtable, Weakhashmap and Identityhashmap would also continue to use the linked list for handling collision Even in the case of frequent collisions.

6) Collision in HashMap is possible because hash function uses hashcode () of key object and Equals () and hashcode () contra CT doesn ' t guarantee different hashcode for different objects. Remember, they guarantee same hash code for the equal object but not the Vice-versa.

7) A collision would occur on Hashtable or HASHMAP when Hashcode () method of the different key objects would return same Val UEs.


That's all about How HashMap in Java handles collisions. In general, this method was called chaining because all objects stored in the same buckets are chained as linked list. In general, all hashes table based classes in Java e.g. HashMap, HashSet, Linkedhashset, Linkedhashmap, Concurrenthsahmap, H Ashtable, Identityhashmap and WEAKHASHMAAP uses linked list to handle collisions.

From JDK 8, a balanced tree would be used to implement chaining instead of linked list to improve worst case performance of HashMap from O (n)to O (log n) for HashMap, Linkedhashmap, and Concurrenthashmap. Since HashSet internally uses HASHMAP and Linkedhashset internally uses LINKEDHASHMAP they would also benefit from this per Formance improvement.


Read More:https://javarevisited.blogspot.com/2016/01/how-does-java-hashmap-or-linkedhahsmap-handles.html#ixzz5kwsojeup

How does Java HashMap or linkedhahsmap handles collisions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.