HashMap implementation in JDK1.8 and JDK1.8HashMap implementation
The implementation of HashMap in JDK1.8 differs greatly from that in JDK1.7. The following describes the implementation in JDK1.8, mainly including the put and get methods.
The constructor is not initialized, but initialized at the first put.
The main logic of the putVal method is as follows:
1. If the array is not initialized (the array length is 0), initialize it first.
2. Calculate the hash value of the key using the hash method, and then calculate the position where the key should be placed in the array.
3. If this location is null, place it here
4. If the position is not empty and the element is a red/black tree, insert it
5. If it is a linked list, it will be used in a traversal table. If an equal element is found, it will be replaced. Otherwise, it will be inserted at the end of the linked list.
6. If the length of the linked list is greater than or equal to 8, the linked list is converted into a red/black tree.
1. Calculate the hash location
2. Check whether the first element is to be found. If yes, return. Otherwise, traverse
Expansion is to move the elements of the old array to the new array.
Summary:
1. The bottom layer of HashMap is implemented by array + two-way linked list + red/black tree.
2. When an element is inserted, a hash method is used to calculate the hash value of the key, and then the location to be inserted is calculated.
3. If this location is empty, insert it directly (packaged as Node)
4. If there is a value in the position, traverse it in sequence. The comparison rule is that if the hash value is the same and the elements with the same key value are treated as the same, the old value is replaced with the new value and the old value is returned.
5. If the element at this position is a red-black tree structure, the same applies to search. If it is found, it is replaced. If it is not found, it is inserted.
Highlights:
In JDK1.8, HashMap is different from JDK1.7 in many aspects.
1. The red and black trees are introduced in 1.8, but not in 1.7.
2. The elements in 1.8 are inserted at the end of the linked list, while the new elements in 1.7 are inserted at the head of the linked list.
3. When resizing, there will be no endless loops in 1.8, and the endless loops in 1.7 will easily occur, and the linked list will not be put upside down.