HashMap and ConcurrentHashMap of Java interview notes

HashMap and ConcurrentHashMap are common interview knowledge points, such as: how to store data, how to expand, how to obtain and delete data. The following content is a summary of the interview experience and reading the source code. I wish you all a successful high-tech job .

In this article, you will gain the following knowledge:

HashMap notes

  • Main attributes
  • data structure
  • put() main process and source code analysis
  • Resize() main process and source code analysis
  • get() main process and source code analysis
  • remove() main process and source code analysis

ConcurrentHashMap notes

  • Main attributes
  • data structure
  • put() main process and source code analysis
  • Resize() main process and source code analysis
  • get() main process and source code analysis
  • remove() main process and source code analysis

Due to limited space, only a part of it is shown here, and the rest of the knowledge points have been organized into documents. Friends in need can click the link below to get it for free!

Link: 1103806531 Password: CSDN

HashMap learning

  • HashMap is a Map interface based on a hash table and allows null keys and null values
  • The implementation of HashMap is not synchronous! ! Therefore it is not thread safe
  • The mapping of HashMap is not ordered!

Before JDK1.8, HashMap is composed of array + linked list! The array is the main body of the HashMap, and the linked list is mainly for solving hash conflicts! ! ! And the existence ("Zipper Law to resolve conflicts")

Hash collision:

​ The hash code value calculated by the hashCode method called by the two objects is the same, resulting in the same array index value calculated

After JDK1.8, there have been big changes when resolving hash value conflicts! ! ! , When the length of the linked list is greater than the threshold (the boundary value of the red-black tree, the default is 8), and the length of the current array is greater than 64, all data at the index position is changed to use the red-black tree to store

Note : It will be judged before converting the linked list into a red-black tree, even if the threshold is greater than 8, but the array length is less than 64, the linked list will not be changed to a red-black tree at this time, but the array will be expanded! ! !

Because when the array is relatively small, you should try to avoid the red-black tree structure, in this case, it will reduce efficiency! Because the red-black tree will rotate left, rotate right, and change colors to maintain balance. At the same time, when the array length is less than 64, the search time is relatively faster. In summary, only when the threshold is greater than 8 and the array length is less than 64, the linked list is converted to a red-black tree.

One, the stored procedure

  • Before jdk1.8, HashMap consists of an array + linked list data structure
  • After jdk1.8, HashMap is composed of array + linked list + red-black tree data structure
Map<Integer, String> map = new HashMap<>();

1. When creating a HashMap collection object, before JDK8, an Entry[] table with a length of 16 was created in the construction method to store key-value pairs. After jdk8, the array is not created at the bottom of the HashMap construction method, but the array is created when the put method is called for the first time. The Node[] table is used to store the key-value pair data.

map.put(1 ," 一号");

2. Assuming that data 1-1 is stored in the hash table, the value is calculated by calling the rewritten hashCode() method in the Integer class according to 1, and then combining the length of the array using a certain algorithm to calculate the space for storing data in the Node array index of,

  • If there is no data in the calculated index space, directly store 1-No. 1 in the array
map.put(2 ," 二号");

3. Store data 2--2 in the hash table, assuming that the index value calculated by the hashCode method calculated by 2 combined with the array length is the same as the index value calculated by the hashCode method calculated by 1 combined with the array length, then at this time The array space is not null, and the bottom layer will compare whether the hash values ​​of 1 and 2 are consistent!

  • If they are inconsistent, draw a node in this space to store the key-value pair (zipper method)
map.put(2 ," 三号");

4. Assuming that the data 2--3 is stored in the hash table, then the index calculated by calling the hashCode method combined with the array length according to 2 must be the same as the previous 2, then compare the hash value of the latter 2 with the previously stored 2 Are equal

  • If the hash values ​​are equal, a hash collision (collision) occurs at this time

    Therefore, the bottom layer will call the equals method in the Integer class of 2 to compare whether the two contents are equal:

  • Equal: the value of the data added later will overwrite the previous value

  • Not equal: then continue to compare with the keys of other data, if they are not equal, draw a node to store the data

Interview question: What algorithm is used to calculate the hash value at the bottom of the hash table? What other algorithms can calculate the hash value?

1. The value of the hashCode method of the key used in the bottom layer is combined with the length of the array to perform unsigned right shift (>>>), bitwise XOR (^), bitwise and (&) to calculate the index

2. There are also the square method, the remainder, and the pseudo-random number method

2. Expansion

In the process of continuously adding data, the problem of capacity expansion will be involved. When the critical value is exceeded (and the location to be stored is not empty), the capacity is expanded.

The default expansion method is: expand to twice the original capacity and copy the original data

When HashMap uses a singly linked list, the time complexity is O(n), and the time complexity of using red-black trees is O(logn)

  • size represents the real-time number of KVs in the HashMap, note that this is not equal to the length of the array
  • threshold (critical value) = capacity (capacity) * loadFactory (load factor)
  • If size exceeds this critical value, resize (expand), and the capacity of HashMap after expansion is twice the previous capacity

Expansion mechanism

When the number of elements in the HashMap exceeds the size of the array (array length * loadFactory), the array will be expanded. The default value of loadFactor (DEFAULT_LOAD_FACTOR) is 0.75, which is a compromise value.

That is, by default, the size of the array is 16, then when the number of elements in the HashMap exceeds 16 * 0.75 = 12 (that is, this value is the threshold or the threshold value!!!), the size of the array is expanded to 2 * 16 = 32, which is doubled

When the number of objects in a linked list in HashMap reaches 8, if the length of the array does not reach 64, then the HashMap will be expanded first. If it has reached 64, then the linked list will become a red-black tree, and the node type is changed from Node becomes the TreeNode type. Of course, if the mapping relationship is removed, the next time the resize method is executed, it is judged that the number of nodes in the tree is less than 6, and the tree will be converted to a linked list! ! !

Without sequential expansion, the tax amount will be redistributed this time, and all the elements in the hash table will be traversed, which is very time-consuming. We should try to avoid resizing

When HashMap expands, the rehash method used is very clever, because each expansion is doubled. Compared with the original calculation (n-1)&hash, it only has one bit more, so the node is either in the original Location, or be assigned to the location "original location + old capacity"

At last

Hope this article is helpful to everyone!

I have also compiled a complete set of video tutorials for architects and systematic materials on java, including java core knowledge points, interview topics, and the latest 20 years of Internet real questions and e-books. Friends in need can click the link below to get it for free!

Link: 1103806531 Password: CSDN

Insert picture description here

Guess you like

Origin blog.csdn.net/XingXing_Java/article/details/108693402