Difference between Hashmap 1.7 and 1.8

In JDK1.7

Use an Entry array to store data, and use the key's hashcode modulo to determine where the key will be placed in the array. If the hashcode is the same, or the result of the hashcode modulo is the same (hash collision), then these keys will be located at In the same cell of the Entry array, these keys will form a linked list.

In the case of particularly poor hashcode, for example, the hashcode of all keys is the same, the linked list may be very long, then put/get operations may need to traverse the linked list

That is to say, the time complexity will degenerate to O(n) in the worst case

 

In JDK1.8

Use a Node array to store data, but this Node may be a linked list structure or a red-black tree structure

If the inserted keys have the same hashcode, these keys will also be located in the same cell of the Node array.

If there are no more than 8 keys in the same grid, use the linked list structure to store.

If there are more than 8, the treeifyBin function will be called to convert the linked list into a red-black tree.

Then even if the hashcodes are exactly the same, due to the characteristics of the red-black tree, only O(log n) overhead is required to find a specific element.

That is to say, the worst time complexity of put/get operations is only O(log n)

 

But really want to take advantage of the benefits of JDK1.8, there is a limitation:

The key object must correctly implement the Compare interface

If the Compare interface is not implemented, or is implemented incorrectly (say all Compare methods return 0)

The HashMap of JDK1.8 is actually slower than JDK1.7

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325068236&siteId=291194637
Recommended