LinkedHashMap source code analysis of Java collection
summary
HashMap is out of order, that is, the put order is not guaranteed to be the same as the traversal order
LinkedHashMap is a subclass of HashMap. It implements its own functions by overriding the related methods of the parent class It preserves the order of insertion If you need the same order of output and input, select this type
LinkedHashMap principle
How does LinkedHashMap ensure the order of input and output?
LinkedHashMap rewrites the entry element of HashMap, which additionally saves the references of the previous element and the next element, thus forming a two-way linked list based on the hash table. Source code:
This linked list maintains a two - way linked list for saving order
Used to specify the order in which the linked list is maintained:
1. Constructor
Its constructor is the constructor that calls HashMap In the constructor of HashMap, the init () method will be called (introduced when introducing HashMap). Lindedhashmap rewrites the init () method and performs relevant initialization in the init () method
2. Storage
Instead of overridden the put method of the parent class, LinkedHashMap rewrites the other methods invoked in the parent class put method to implement its own functions. The parent put method is as follows:
The rewriting method of lindedhashmap is as follows:
3. Read
LinkedHashMap overrides the get method of the parent class:
Actually, after calling the parent class getentry method to obtain the searched elements, judge whether to record the access order Because the addition and deletion of linked list are constant level, it will not bring performance loss
4. Sorting mode
Lindedhashmap defines a boolean variable accessorder. If it is true, it is sorted according to the access order; if it is false, it is sorted according to the insertion order The default is false;
In fact, LinkedHashMap is almost the same as HashMap, except that LinkedHashMap defines an entry element header. A two-way linked list is established through the combination of before, after and header in the header to realize the order of elements