[Source code learning] LinkedHashMap

This article talks about LinkedHashMap is very good.
Before LinkedHashMap, let me talk about the principle of HashMap. Refer to this blog post. This is the principle of HashMap writing data. In order to reduce conflicts, the hash algorithm is obtained by shifting the hashcode value of the key and its hashcode by 16 bits to the right. Value is obtained by XOR operation.
Insert picture description here
LinkedHashMap can be said to be a collection of HashMap and LinkedList. It not only uses the data structure of HashMap, but also borrows the structure of LinkedList doubly linked list. The basic data type is still Entry static internal class. Its structure is as follows, before and after point to guarantee the order, in the same hash list, use next to point to the next node.

static class Entry<K,V> extends HashMap.Node<K,V> {
    
    
    Entry<K,V> before, after;
    Entry(int hash, K key, V value, Node<K,V> next) {
    
    
        super(hash, key, value, next);
    }
}

When a new node is created, the newly created node p is used as the tail node. Of course, if the first node is stored, it is both a head node and a tail node. At this time, the before and after of node p are both null. Otherwise, establish a linked list relationship with the last end node, set the previous node (before) of the current end node p to the last end node last, and set the last node (after) of the last end node last to At the current end node p, the doubly linked list function is realized through this method, and the values ​​of before, after, head, and tail are set. A more critical method in LinkedHashMap: afterNodeAccess guarantees that the operated Node node is always at the end, thus ensuring the order of reading, which will be used when calling the put method and the get method.

Insert picture description here

Guess you like

Origin blog.csdn.net/u010659877/article/details/108768325