之前文章《HashMap源码分析》中我们分析了HashMap的源码,本篇我们来分析LinkedHashMap的源码。同样进一步阅读之前强烈建议先浏览一下之前文章《《Java Generics and Collections》笔记-Lists/Maps》中关于Maps的部分,并熟悉《HashMap源码分析》中关于HashMap的介绍。
我们知道HashMap与LinkedHashMap的最大区别就是后者可以记录(访问或者插入)顺序。本篇我们重点分析它是如何实现的。
首先我们还是先回顾一下HashMap,下图来自之前的文章:
前面的文章中已经详细介绍了,这里就不再赘述。
继承关系:
147 public class LinkedHashMap<K,V>
148 extends HashMap<K,V>
149 implements Map<K,V>
LinkedHashMap中增加了一个成员变量accessOrder,如下:
159 /**160 * The iteration ordering method for this linked hash map: <tt>true</tt>
161 * for access-order, <tt>false</tt> for insertion-order.
164 */
165 private final boolean accessOrder;
具体注释中已经指明了。
另外增加的一个成员为header,如下:
154 /**
155 * The head of the doubly linked list.
156 */
157 private transient Entry<K,V> header;
注释中也说明了,LinkedHashMap采用的是双向链表,header是链表首部,通过增加一个header,简化了边界条件的判断,这一点在后面的插入、删除等操作中可以体会到。
上面可以看到header的类型为Entry<K,V>,我们来看一下:
318 * LinkedHashMap entry.
319 */
320 private static class Entry<K,V>extends HashMap.Entry<K,V> {
321 // These fields comprise the doubly linked list used for iteration.
322 Entry<K,V> before, after;
323
324 Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
325 super(hash, key, value, next);
326 }
327
328 /**
329 * Removes this entry from the linked list.
330 */
331 private void remove() {
332 before.after = after;
333 after.before = before;
334 }
335 就像前面所说,由于添加了首部header,删除元素变得简单(不需要判断为null的情况)。
336 /**
337 * Inserts this e