Linkedhashmap Analysis:
/** * 双向链表,用来维护存储的元素顺序,根据accessOrder来判断是存储 * 访问顺序还是插入顺序。 * 因为LinkedHashMap是继承了HashMap,LinkedHashMap其实维护了两组数 * 据,底层是HashMap中的Entry[] table */private transient Entry<K,V> header;
```java/*** true表示按照访问顺序迭代,false时表示按照插入顺序* 默认情况下都是false,只有一个构造方法中提供设置参数* LRU:Least Recently Used最近最少使用算法 */private final boolean accessOrder;
```java/*** 可以设置accessOrder的构造方法*/public LinkedHashMap(int initialCapacity, float loadFactor ,boolean accessOrder) { super(initialCapacity, loadFactor); this.accessOrder = accessOrder; }
```java/***它是在HashMap构造方法中最后被调用的,在HashMap中无意义,专门给继承类*覆盖的。这里初始化了LinkedHashMap的header。**/void init() { header = new Entry<>(-1, null, null, null); header.before = header.after = header;}
' java/*** is called in the Resize method, Linkedhashmap overrides this method, transfer in the original hashmaph iterates through each element in the table entry, Then each element is then traversed to get each entry, re-hash into the newtable. * While Linkedhashmap has maintained a header doubly linked list, it simply loops the header, improving iteration efficiency. */void transfer (hashmap.entry[] newtable) {int newcapacity = newtable.length; for (entry<k,v> e = Header.after; E! = header; e = e.after) {int index = indexfor (E.hash, newcapacity); E.next = Newtable[index]; Newtable[index] = e; } }
"java/*** for the header of the two-way list and the underlying HashMap table in co-maintenance, Linkedhashmap covered void addentry (int hash, K key, V value, int bucketindex) and void createentry (int hash, K key, V value, int bucketindex), while overwriting void Recordaccess (HashMap m) in class entry to implement header ordering ***/voi d addentry (int hash, K key, V value, int bucketindex) {createentry (hash, key, value, Bucketindex); Remove eldest entry if instructed, else grow capacity if appropriate entry<k,v> eldest = Header.after; if (Removeeldestentry (eldest)) {Removeentryforkey (Eldest.key); } else {if (size >= threshold) Resize (2 * table.length); The}}/*** method returns false by default, providing the method to be modified to determine if the last entry needs to be removed, such as removing the oldest element in the cache. */protected Boolean removeeldestentry (map.entry<k,v> eldest) {return false; }//also maintains headervoid createentry (int hash, K key, V value, int bucketindex) {hashmap.entry<k,v> old = Table[bucket Index]; entry<k,v> e = new entry<> (hash, key, value, old); Table[bucketindex] = e; E.addbefore (header); size++;} Inserted before the header private void Addbefore (Entry<k,v> existingentry) {after = Existingentry; before = Existingentry.before; Before.after = this; After.before = this; }//when a Get or set method is called, this method is called to maintain the order of the elements in the header. void Recordaccess (hashmap<k,v> m) {linkedhashmap<k,v> LM = (linkedhashmap<k,v>) m; if (lm.accessorder) {lm.modcount++; Remove (); Addbefore (Lm.header); } }
Java Notes (2)-linkedhashmap