LinkedHashMap源码分析

本文深入分析LinkedHashMap的源码,揭示其与HashMap的区别——记录顺序。通过研究其内部结构,如accessOrder变量和header双向链表节点,理解LinkedHashMap如何实现顺序功能。
摘要由CSDN通过智能技术生成

之前文章《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>,我们来看一下:

317     /**
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值