1. Linkedhashmap Overview:
Linkedhashmap is a hash table and link list implementation of the map interface with a predictable iteration order. This implementation provides all the optional mapping operations and allows NULL values and NULL keys to be used. This class does not guarantee the order of the mappings, especially because it does not guarantee that the order is constant.
The difference between LINKEDHASHMAP implementations and HashMap is that the latter maintains a double-link list that runs on all items. This list of links defines the order of iterations, which can be in the order of insertion or in the order of access.
Note that this implementation is not synchronous. If more than one thread accesses the linked hash map at the same time, and at least one of the threads modifies the mapping from the structure, it must remain externally synchronized.
2. Implementation of Linkedhashmap:
For Linkedhashmap, it inherits all the elements with HashMap, the underlying use of a hash table, and a doubly linked list. Its basic operation is similar to the parent class HashMap, which implements its own list of linked properties by overriding the methods associated with the parent class. Let's analyze the source code of Linkedhashmap:
1) Entry elements:
Linkedhashmap uses the same hash algorithm as HASHMAP, but it redefined the elements saved in the array entry, which, in addition to saving references to the current object, also holds references to the previous element before and the next element after. Thus, on the basis of the hash table constitutes a two-way link list. Look at the source code:
Java code
- /**
- * The table header element of the doubly linked list.
- */
- Private transient entry<k,v> header;
- /**
- * The entry element of the Linkedhashmap.
- * Inherits the entry element of HashMap, and holds the reference to its previous element before and the next element after.
- */
- Private static class entry<k,v> extends hashmap.entry<k,v> {
- Entry<k,v> before, after;
- ......
- }
2) Initialize:
It can be seen from the source code that, in the construction method of Linkedhashmap, the relative construction method of the parent class HashMap is actually called to construct a table array that is stored at the bottom. Such as:
Java code
- Public Linkedhashmap (int initialcapacity, float loadfactor) {
- Super (initialcapacity, loadfactor);
- Accessorder = false;
- }
The related construction methods in HashMap:
Java code
- Public HashMap (int initialcapacity, float loadfactor) {
- if (Initialcapacity < 0)
- throw New IllegalArgumentException ("Illegal initial capacity:" +
- initialcapacity);
- if (initialcapacity > Maximum_capacity)
- initialcapacity = maximum_capacity;
- if (loadfactor <= 0 | | Float.isnan (loadfactor))
- throw New IllegalArgumentException ("illegal load factor:" +
- Loadfactor);
- //Find a power of 2 >= initialcapacity
- int capacity = 1;
- While (capacity < initialcapacity)
- Capacity <<= 1;
- this.loadfactor = Loadfactor;
- Threshold = (int) (capacity * loadfactor);
- Table = new entry[capacity];
- Init ();
- }
We already know that the entry element of Linkedhashmap inherits the entry of HashMap and provides the function of the doubly linked list. In the above HashMap constructor
, the init () method is called at the end, and the associated initialization, which is meaningless in the implementation of HashMap, is provided to the subclass to implement related initialization calls.
Linkedhashmap overrides the Init () method, which further implements the initialization of its element entry after the constructor method of the calling parent class is completed.
Java code
- void Init () {
- Header = new Entry<k,v> (-1, null, NULL , null );
- Header.before = Header.after = header;
- }
3) Storage:
Instead of overriding the put method of the parent class HashMap, Linkedhashmap overrides the child method of the put method call of the parent class HashMap void addentry (int hash, K key, V value, int bucketindex) and void createentry (int hash, K key, V value, int bucketindex), provides the implementation of its own unique two-way link list.
Java code
- void AddEntry (int hash, K key, V value, int bucketindex) {
- //Call the Create method to add the new element to the map as a doubly linked list.
- Createentry (hash, key, value, Bucketindex);
- //delete policy definitions for least recently used elements
- entry<k,v> eldest = Header.after;
- if (removeeldestentry (eldest)) {
- Removeentryforkey (Eldest.key);
- } Else {
- if (size >= threshold)
- Resize (2 * table.length);
- }
- }
Java code
- void Createentry (int hash, K key, V value, int bucketindex) {
- hashmap.entry<k,v> old = Table[bucketindex];
- entry<k,v> e = new entry<k,v> (hash, key, value, old);
- Table[bucketindex] = e;
- //Call the element's Addbrefore method to add the element to the hash, two-way link list.
- E.addbefore (header);
- size++;
- }
Java code
- Private void Addbefore (entry<k,v> existingentry) {
- after = Existingentry;
- before = Existingentry.before;
- Before.after = this ;
- After.before = this ;
- }
4) Read:
Linkedhashmap overrides the Get method of the parent class HashMap, actually after calling the parent class Getentry () method to get the element to find, and then judging when the sort mode accessorder to true, the record access order, Adds the most recently accessed element to the table header of the doubly linked list and removes it from its original location. Because of the increase of the list, delete operation is constant level, it does not bring the loss of performance.
Java code
- Public V get (Object key) {
- //Call the Getentry () method of the parent class HashMap to get the element you want to find.
- Entry<k,v> e = (entry<k,v>) getentry (key);
- if (e = = null)
- return null;
- //record access order.
- E.recordaccess (this);
- return e.value;
- }
Java code
- void Recordaccess (hashmap<k,v> m) {
- linkedhashmap<k,v> lm = (linkedhashmap<k,v>) m;
- //If the iteration order of LINKEDHASHMAP is defined as the access order,
- //Delete the element from the previous location and add the newly accessed element to the list header.
- if (lm.accessorder) {
- lm.modcount++;
- Remove ();
- Addbefore (Lm.header);
- }
- }
5) Sort mode:
Linkedhashmap defines the sort mode accessorder, which is a Boolean variable, true for the access order, or FALSE for the insertion order.
Java code
- Private Final Boolean accessorder;
In general, you do not have to specify a sort pattern, whose iteration order is the default for the insertion order. Look at the construction methods of Linkedhashmap, such as:
Java code
- Public Linkedhashmap (int initialcapacity, float loadfactor) {
- Super (initialcapacity, loadfactor);
- Accessorder = false;
- }
These construction methods will default to the ordering mode for the insertion order. If you want to construct a linkedhashmap and plan to save the elements in the order of least recent visits to the most recent visits (that is, the order of access), use the following construction method to construct the Linkedhashmap:
Java code
- Public Linkedhashmap (int initialcapacity,
- float Loadfactor,
- Boolean Accessorder) {
- Super (initialcapacity, loadfactor);
- this.accessorder = Accessorder;
- }
The iteration order of the hash map is the order in which the entries are last accessed, a mapping that is well suited for building LRU caches. Linkedhashmap provides the removeeldestentry (map.entry<k,v> eldest) method, which is called by put and Putall when new entries are inserted into the map. The method can provide an implementation that removes the oldest entry each time a new entry is added, and returns false by default, so that the mapping behaves like a normal mapping, where the oldest element is never removed.
Java code
- Protected Boolean removeeldestentry (map.entry<k,v> eldest) {
- return false;
- }
This method usually does not modify the mappings in any way, but instead allows the mappings to self-modify under the guidance of their return values. It is convenient to build an LRU cache with this mapping, which allows mappings to reduce memory loss by removing old entries.
For example: Override this method to maintain a stable state of only 100 entries, and delete the oldest entries each time a new entry is added.
Java code
- Private static final int max_entries = 100;
- Protected Boolean removeeldestentry (map.entry eldest) {
- return size () > max_entries;
- }
3. Related notes:
1) Before reading this article, please understand: in-depth Java Collection Learning Series: HASHMAP implementation principle.
2) The implementation principle of the related hashset, please refer to: In-depth Java Collection Learning Series: hashset implementation principle.
3) The implementation principle of the related linkedhashset, please refer to: In-depth Java Collection Learning Series: Linkedhashset implementation principle.
http://zhangshixi.iteye.com/blog/673789
In-depth Java Collection Learning Series: LINKEDHASHMAP Implementation principle