HashMap uses a hash table to store data and handles conflicts with a zipper method . Linkedhashmap inherits from HashMap, and has a list of its own, which uses the linked list to store data without conflicts.
LinkedList and Linkedhashmap use a two-way loop linked list , but LinkedList stores simple data, not "key-value pairs."
LinkedList and Linkedhashmap can maintain the sequence of content , but HashMap does not maintain order.
Public class Linkedhashmap<k,v> extends hashmap<k,v> implements map<k,v>
HashMap's Init method is not implemented, but Linkedhaqshmap has implemented it:
void init () { // Initialize the header of a entry type newnullnull NULL ); = Header.after = header; }
InLinkedhashmaphas one moreAccessorderVariable,He represents a sequence of iterations,If theTrueare sorted in reading order(Read more in the back of the list,The less you read, the more front of the list,Lru, least recently used),If theFalseSort by Insert Order.FromLinkedhaqshmapThe former4A construction method can be seen, AccessorderDefault isfalse, it is sorted in order of insertion.
void recordaccess (hashmap<k,v> m) { linkedhashmap<K,V> lm = (linkedhashmap<k,v >) m; if (LM. Accessorder) { lm.modcount+ +; remove (); Addbefore (lm.header); } }
In the LRU algorithm, the least used pages are swapped out and most recently used are likely to be used later.
He determines the Accessorder attribute, if true, executes an algorithm called LRU , removes the newly accessed entry and adds it to the front of the header, so that the iteration The iteration order is changed by prioritizing the entry (not the chain header) of the most frequently accessed recently.
void addentry (intint bucketindex) { createentry (hash, key, value, Bucketindex); Entry<K,V> eldest = header.after; if (Removeeldestentry (eldest)) { removeentryforkey (eldest.key); Else { if (size >= threshold) Resize (2 * table.length);} }
protected boolean removeeldestentry (map.entry<k,v> eldest) { //always returns false
returnfalse;}
heuristic : If you want to use a map as a cache and limit the size , simply inherit linkedhashmap and rewrite Removeeldestentry (Entry <K,V> eldest) method , like this:
Private Static Final int Max_entries =protectedboolean removeeldestentry (map.entry eldest) { return size () > max_entries;}
To implement the most recently used (LRU) cache:
Import Java.util.LinkedHashMap; Import publicextends linkedhashmap<k, v> { privateint cacheSize; Public LRUCache (int cacheSize) { supertrue); Sort Policy this . cacheSize = cacheSize; }
Java Collection (--LINKEDHASHMAP) source code Analysis