JAVA—HashMap

Some study notes on hashmap

1. The underlying implementation principle of HashMap

  In JDK1.7, HashMap is composed of an array and a linked list. After JDK1.8, a new red-black tree composition structure is added. When the linked list is greater than 8 and the capacity is greater than 64, the linked list structure will be transformed into a red-black tree structure. .

  The elements in the array are called hash buckets, and each hash bucket has four fields, hash, key, value, and next representing the next node.

 

2. JDK1.8 optimization of HashMap

  (1) The red-black tree is added, because the long linked list will affect the performance of HashMap and reduce the efficiency, and the red-black tree has the characteristics of rapid addition, deletion and modification, which can effectively improve efficiency.

  (2) Dead loop optimization, linked list insertion method is changed to tail positive sequence insertion

  (3) Optimize expansion, JDK1.8 chooses to use high-order operation e.hash & olcCap to determine whether the element needs to be moved during expansion, instead of recalculating the hash value.

such as:

key1.hash=10 0000 1010

oldCap = 16 0001 0000

The higher one result is 0, 0 means that the position of the element will not change during expansion

key2.hash=10 0001 0001

oldCap = 16 0001 0000

At this time, the higher one is 1, which means that the position of the element has changed during the expansion. The new subscript position is equal to the original subscript position + the length of the original array

 

3. HashMap infinite loop

  The main reason for the endless loop before JDK1.7 is that HashMap is not thread safe and the insertion method before JDK1.8 is the first reverse insertion. Assuming that the default size of a HashMap is 2, there was originally a key (5), and now two threads are created. T1 adds the element key (3) to the HashMap, t2 adds the element key (7), and t1 assigns the value to next. t2 gets the right to use the CPU. At this time, e in t1 points to key (3), and next points to key (7). Then t2 rehashes and the linked list order is reversed. At this time, the next key (7) is key (3). The query has formed a loop call for a long time, resulting in an endless loop.

 

Guess you like

Origin www.cnblogs.com/zucc-31701019/p/12705804.html