HashMap&LinkedHashMap&LruCache
1、HashMap

hashmap
1.1、 put函式的實現
public V put(K key, V value) { // 對key的hashCode()做hash return putVal(hash(key), key, value, false, true); } final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; // tab為空則建立 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 計算index,並對null做處理 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; // 節點存在 if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; // 該鏈為樹 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); // 該鏈為連結串列 else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } // 寫入 if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; // 超過load factor*current capacity,resize if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
put函式大致的思路為:
1、對key的hashCode()做hash,然後再計算它在陣列中的index;
2、如果沒碰撞直接放到bucket裡;
3、如果碰撞了,以連結串列的形式存在buckets後;
4、如果碰撞導致連結串列過長(大於等於TREEIFY_THRESHOLD),就把連結串列轉換成紅黑樹;
5、如果節點已經存在就替換old value(保證key的唯一性);
6、如果bucket滿了(超過load factor*current capacity),就要resize。
1.2、get函式的實現
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { // 直接命中 if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; // 未命中 if ((e = first.next) != null) { // 在樹中get if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); // 在連結串列中get do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }
get大致思路如下:
0、對key的hashCode()做hash,然後再計算它在陣列中的index;
1、如果hash相等並且key相等,直接命中;
2、如果有衝突,就去樹中或者連結串列中尋找;
3、若為樹;O(logn);
4、若為連結串列,O(n)。
1.3、hash實現
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }

hash實現
高16bit不變,低16bit和高16bit做了一個異或,計算下標的方式是(n - 1) & hash,異或一下,在bucket的n比較小的時,也可以讓高16位和低16位都引數下標計算,有效緩解碰撞。
1.4、hashmap原理速記
hashmap是採用陣列+連結串列的形式去儲存鍵值對的,在java1.8中為了更快的查詢,它會在連結串列超過一定長度時將連結串列轉換成紅黑樹;它的put過程大概是這樣的,,,;它的get過程大概是這樣的,,,。
2、LinkedHashMap

linkedhashmap
LinkedHashMap是Hashmap+雙向連結串列,並且依靠雙向連結串列保持順序。
2.1、三個重點實現的函式
// Callbacks to allow LinkedHashMap post-actions void afterNodeAccess(Node<K,V> p) { } void afterNodeInsertion(boolean evict) { } void afterNodeRemoval(Node<K,V> p) { }
LinkedHashMap繼承於HashMap,因此也重新實現了這3個函式,顧名思義這三個函式的作用分別是:節點訪問後、節點插入後、節點移除後做一些事情。
2.1.1、afterNodeAccess函式
void afterNodeAccess(Node<K,V> e) { // move node to last LinkedHashMap.Entry<K,V> last; // 如果定義了accessOrder,那麼就保證最近訪問節點放到最後 if (accessOrder && (last = tail) != e) { LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; p.after = null; if (b == null) head = a; else b.after = a; if (a != null) a.before = b; else last = b; if (last == null) head = p; else { p.before = last; last.after = p; } tail = p; ++modCount; } }
意思是如果定義了accessOrder,就把這個節點從雙向連結串列原位置刪除然後放到最後。(注意此時節點的next地址是不變的,改變的只是它的before和after地址)看似程式碼很亂,畫圖很容易理解。
2.1.2、afterNodeInsertion函式
void afterNodeInsertion(boolean evict) { // possibly remove eldest LinkedHashMap.Entry<K,V> first; // 如果定義了移除規則,則執行相應的移除 if (evict && (first = head) != null && removeEldestEntry(first)) { K key = first.key; removeNode(hash(key), key, null, false, true); } }
意思是 ,如果定義了移除規則removeEldestEntry,則執行相應的移除。(移除的是雙向連結串列頭結點,最近最少使用的節點)。
2.1.3、afterNodeRemoval函式
void afterNodeRemoval(Node<K,V> e) { // unlink // 從連結串列中移除節點 LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; p.before = p.after = null; if (b == null) head = a; else b.after = a; if (a == null) tail = b; else a.before = b; }
意思是節點從hash表中刪除後也要從雙向連結串列中刪除。
2.2、put和get函式
put函式在LinkedHashMap中未重新實現,只是實現了afterNodeAccess和afterNodeInsertion兩個回撥函式,在hashmap中的put方法中有對應呼叫。
get函式則重新實現並加入了afterNodeAccess來保證訪問順序,下面是get函式的具體實現:
public V get(Object key) { Node<K,V> e; if ((e = getNode(hash(key), key)) == null) return null; if (accessOrder) afterNodeAccess(e); return e.value; }
2.3、LinkedHashMap原理速記
LinkedHashMap是Hashmap+雙向連結串列構成的,並且依靠雙向連結串列保持順序。
accessorder模式下,一個節點被訪問之後就會將它從雙向連結串列的原位置刪除並放到最後,當一個節點插入後,如果重寫了移除規則removeEldestEntry方法,則移除雙向連結串列的首節點,即最近最少使用的節點,以此來實現LRU。
3、LruCache
3.1、LruCache構造
public LruCache(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } this.maxSize = maxSize; this.map = new LinkedHashMap<K, V>(0, 0.75f, true); }
LruCache使用accessorder模式的LinkedHashMap構造。
3.2、put方法
public final V put(K key, V value) { //不可為空,否則丟擲異常 if (key == null || value == null) { throw new NullPointerException("key == null || value == null"); } V previous; synchronized (this) { //插入的快取物件值加1 putCount++; //增加已有快取的大小 size += safeSizeOf(key, value); //向map中加入快取物件 previous = map.put(key, value); //如果已有快取物件,則快取大小恢復到之前 if (previous != null) { size -= safeSizeOf(key, previous); } } //entryRemoved()是個空方法,可以自行實現 if (previous != null) { entryRemoved(false, key, previous, value); } //調整快取大小(關鍵方法) trimToSize(maxSize); return previous; }
put()方法將鍵值對插入儲存到LinkedHashMap中,然後呼叫 trimToSize()方法,來判斷快取是否已滿,如果滿了就是使用Lru演算法進行刪除。
trimToSize方法
public void trimToSize(int maxSize) { //死迴圈 while (true) { K key; V value; synchronized (this) { //如果map為空並且快取size不等於0或者快取size小於0,丟擲異常 if (size < 0 || (map.isEmpty() && size != 0)) { throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!"); } //如果快取大小size小於最大快取,或者map為空,不需要再刪除快取物件,跳出迴圈 if (size <= maxSize || map.isEmpty()) { break; } //迭代器獲取第一個物件,即隊尾的元素,近期最少訪問的元素 Map.Entry<K, V> toEvict = map.entrySet().iterator().next(); key = toEvict.getKey(); value = toEvict.getValue(); //刪除該物件,並更新快取大小 map.remove(key); size -= safeSizeOf(key, value); evictionCount++; } entryRemoved(true, key, value, null); } }
trimToSize()方法不斷地刪除LinkedHashMap中隊頭的節點,即最近最少訪問的節點,直到快取大小小於最大值。
3.2、get方法
public final V get(K key) { //key為空丟擲異常 if (key == null) { throw new NullPointerException("key == null"); } V mapValue; synchronized (this) { //獲取對應的快取物件 //get()方法會實現將訪問的元素更新到佇列頭部的功能 mapValue = map.get(key); if (mapValue != null) { hitCount++; return mapValue; } missCount++; }
呼叫LinkedHashMap的get方法去獲取資料,並維持訪問順序。
3.2、LruCache原理速記
LruCache內部維護了一個LinkedHashMap,並使用LinkedHashMap的accessorder模式去實現Lru演算法,LinkedHashMap是Hashmap+雙向連結串列構成的,並且依靠雙向連結串列保持順序。accessorder模式下,一個節點被訪問之後就會將它從雙向連結串列的原位置刪除並放到最後,當一個節點插入後,如果大於了LruCache的最大容量,就會移除雙向連結串列的首節點,即最近最少使用的節點,以此來實現LRU。
4、LinkedHashMap實現LruCache
public class LRUCache <K, V>{ private int capacity; private Map<K, V> cache; public LRUCache(int capacity) { this.capacity = capacity; this.cache = new java.util.LinkedHashMap<K, V> (capacity, 0.75f, true) { // 定義put後的移除規則,大於容量就刪除eldest protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; } }; } public V get(K key) { return cache.get(key); } public V put(K key, V value) { return cache.put(key, value); } }