LinkedHashMap
实质是HashMap+LinkedList
,提供了顺序访问的功能;因此在看这篇博客以前最好先看一下我以前的两篇博客,HashMap 相关 和 LinkedList 相关;html
1、总体结构
1. 定义
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V> {}
<img src="https://img2018.cnblogs.com/blog/1119937/201901/1119937-20190121094619602-2085192613.png" width = "350" alt="LinkedHashMap 结构" align=center />java
从上述定义中也能看到LinkedHashMap
其实就是继承了HashMap
,并加了双向链表记录顺序,代码和结构自己不难,可是其中结构的组织,代码复用这些地方十分值得咱们学习;具体结构如图所示:node
<img src="https://img2018.cnblogs.com/blog/1119937/201901/1119937-20190121094715988-607190851.png" width = "600" alt="LinkedHashMap 结构" align=center />app
2. 构造函数和成员变量
public LinkedHashMap(int initialCapacity, float loadFactor) {} public LinkedHashMap(int initialCapacity) {} public LinkedHashMap() {} public LinkedHashMap(Map<? extends K, ? extends V> m) {} public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {} /** * The iteration ordering method for this linked hash map: <tt>true</tt> * for access-order, <tt>false</tt> for insertion-order. * @serial */ final boolean accessOrder;
能够看到LinkedHashMap
的5个构造函数和HashMap
的做用基本是同样的,都是初始化initialCapacity
和loadFactor
,可是多了一个accessOrder
,这也是LinkedHashMap
最重要的一个成员变量了;ide
- 当
accessOrder
为true
的时候,表示LinkedHashMap
中记录的是访问顺序,也是就没放get一个元素的时候,这个元素就会被移到链表的尾部; - 当
accessOrder
为false
的时候,表示LinkedHashMap
中记录的是插入顺序;
3. Entry关系
<img src="https://img2018.cnblogs.com/blog/1119937/201901/1119937-20190121094800076-1747634277.png" width = "800" alt="hashmap_entry" align=center />函数
扎眼一看可能会以为HashMap
体系的节点继承关系比较混乱;一因此这样设计由于源码分析
LinkedHashMap
继承至HashMap
,其中的节点一样有普通节点和树节点两种;而且树节点不多使用;- 如今的设计中,树节点是能够彻底复用的,可是
HashMap
的树节点,会浪费双向链表的能力; - 若是不这样设计,则至少须要两条继承关系,而且须要抽出双向链表的能力,整个继承体系以及方法的复用会变得很是复杂,不利于扩展;
2、重要方法
上面咱们已经讲了LinkedHashMap
就是HashMap+链表
,因此咱们只须要在结构有可能改变的地方加上链表的修改就能够了,结构可能改变的地方只要有put/get/replace
,这里须要注意扩容的时候虽然结构改变了,可是节点的顺序仍然保持不变,因此扩容能够彻底复用;学习
1. put 方法
- 未找到key时,直接在最后添加一个节点
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) { LinkedHashMap.Entry<K,V> p = new LinkedHashMap.Entry<K,V>(hash, key, value, e); linkNodeLast(p); return p; } TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) { TreeNode<K,V> p = new TreeNode<K,V>(hash, key, value, next); linkNodeLast(p); return p; } private void linkNodeLast(LinkedHashMap.Entry<K,V> p) { LinkedHashMap.Entry<K,V> last = tail; tail = p; if (last == null) head = p; else { p.before = last; last.after = p; } }
上面代码很简单,可是很清晰的将添加节点到最后的逻辑抽离的出来;ui
- 找到key,则替换value,这部分须要联系 HashMap 相关 中的put方法部分;
// HashMap.putVal ... // 若是找到key if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } // 若是没有找到key ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; ...
在以前的HashMap
源码分析当中能够看到有几个空的方法this
void afterNodeAccess(Node<K,V> p) { } void afterNodeInsertion(boolean evict) { } void afterNodeRemoval(Node<K,V> p) { }
这三个就是用来调整链表位置的事件方法,能够看到HashMap.putVal
中就使用了两个,
void afterNodeAccess(Node<K,V> e) { // move node to last LinkedHashMap.Entry<K,V> last; 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; } }
afterNodeAccess
能够算是LinkedHashMap
比较核心的方法了,当访问了一个节点的时候,若是accessOrder = true
则将节点放到最后,若是accessOrder = false
则不变;
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); } } protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { return false; }
afterNodeInsertion
方法是插入节点后是否须要移除最老的节点,这个方法和维护链表无关,可是对于LinkedHashMap
的用途有很大做用,后天会举例说明;
2. 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; } public V getOrDefault(Object key, V defaultValue) { Node<K,V> e; if ((e = getNode(hash(key), key)) == null) return defaultValue; if (accessOrder) afterNodeAccess(e); return e.value; }
get方法主要也是经过afterNodeAccess
来维护链表位置关系; 以上就是LinkedHashMap
链表位置关系调整的主要方法了;
3. containsValue 方法
public boolean containsValue(Object value) { for (LinkedHashMap.Entry<K,V> e = head; e != null; e = e.after) { V v = e.value; if (v == value || (value != null && value.equals(v))) return true; } return false; }
能够看到LinkedHashMap
还重写了containsValue
,在HashMap
中寻找value的时候,须要遍历全部节点,他是遍历每一个哈希桶,在依次遍历桶中的链表;而在LinkedHashMap
里面要遍历全部节点的时候,就能够直接经过双向链表进行遍历了;
3、应用
public class Cache<K, V> { private static final float DEFAULT_LOAD_FACTOR = 0.75f; private final int MAX_CAPACITY; private LinkedHashMap<K, V> map; public Cache(int capacity, boolean accessOrder) { capacity = (int) Math.ceil((MAX_CAPACITY = capacity) / DEFAULT_LOAD_FACTOR) + 1; map = new LinkedHashMap(capacity, DEFAULT_LOAD_FACTOR, accessOrder) { @Override protected boolean removeEldestEntry(Map.Entry eldest) { return size() > MAX_CAPACITY; } }; } public synchronized void put(K key, V value) { map.put(key, value); } public synchronized V get(K key) { return map.get(key); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Map.Entry entry : map.entrySet()) { sb.append(String.format("%s:%s ", entry.getKey(), entry.getValue())); } return sb.toString(); } }
以上是就是一个LinkedHashMap
的简单应用,
- 当
accessOrder = true
时,就是LRUCache, - 当
accessOrder = false
时,就是FIFOCache;
// LRUCache Cache<String, String> cache = new Cache<>(3, true); cache.put("a", "1"); cache.put("b", "2"); cache.put("c", "3"); cache.put("d", "4"); cache.get("c"); System.out.println(cache);
// 打印:b:2 d:4 c:3
// FIFOCache Cache<String, String> cache = new Cache<>(3, false); cache.put("a", "1"); cache.put("b", "2"); cache.put("c", "3"); cache.put("d", "4"); cache.get("c"); System.out.println(cache);
// 打印:b:2 c:3 d:4
总结
- 整体而言
LinkedHashMap
的代码比较简单,可是我以为里面代码的组织,逻辑的提取等方面特别值得借鉴;