jdk源码阅读笔记-LinkedHashMap

 Map是Java collection framework 中重要的组成部分,特别是HashMap是在我们在日常的开发的过程中使用的最多的一个集合。但是遗憾的是,存放在HashMap中元素都是无序的,原因是我们在put或get数据的时候都是根据key的hash值来确定元素的位置。在具体的业务场景中,我们更多的希望对于HashMap集合能够进行顺序访问,好在 jdk 中已经给我们提供了一种解决方案,那就是LinkedHashMap。该类继承与HashMap,因此HashMap拥有的特性它都有,同时还具备其他的特性,比如实现了插入顺序排序和访问顺序排序,默认以插入顺序排序。同时也能够利用LinkedHashMap实现LRU算法。LinkedHashMap api很少,基本都是调用HashMap的方法,所以建议熟悉HashMap源码之后再来看这篇文章,我之前也写过【

  从上图可以看到HashMap的数据结构位数组+单向链表,数据存放在链表的node节点上,每个node节点上都有一个指针指向下一个节点,每个数组index上的链表跟其他的index上面的链表是部相互链接的。LinkedHashMap在部破坏HashMap的结构基础之上,每个node节点都额外增加了两个指针,分别指向了前一个节点和下一个节点,所以在HashMap上所有的node节点形成了一条双向链表,每次添加往LinkedHashMap put数据的时候都将节点放在双向链表的最后位置,从而实现了插入顺序排序。在LinkedHashMap中,节点的定义如下:

复制代码
/**      * HashMap.Node subclass for normal LinkedHashMap entries.      */    static class Entry<K,V> extends HashMap.Node<K,V> {         Entry<K,V> before, after;         Entry(int hash, K key, V value, Node<K,V> next) {             super(hash, key, value, next);         }     }
复制代码

 

   节点继承与HashMap的 Node内部类,但是又额外添加了两个属性,before和after,分别指向前一个节点和后一个节点,形成一个双向链表。

 

  二、LinkedHashMap类结构

复制代码
public class LinkedHashMap<K,V>     extends HashMap<K,V>     implements Map<K,V> {         ....... }
复制代码

   LinkedHashMap继承了HashMap,所以拥有HashMap的所有特性。

 

  三、成员变量

复制代码
    /**      * The head (eldest) of the doubly linked list.      */     transient LinkedHashMap.Entry<K,V> head;      /**      * The tail (youngest) of the doubly linked list.      */     transient LinkedHashMap.Entry<K,V> tail;      /**      * 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在HashMap的基础之上添加了head、tail和accessOrder属性:

  head:双向链表的表头

  tail: 双向链表的表尾

  accessOrder:排序的标志。默认为false,按插入顺序排序。可以通过构造方法设置为true,按访问顺序排序。

 

  四、构造方法

复制代码
    /**      * Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance      * with the specified initial capacity and load factor.      *      * @param  initialCapacity the initial capacity      * @param  loadFactor      the load factor      * @throws IllegalArgumentException if the initial capacity is negative      *         or the load factor is nonpositive      */    public LinkedHashMap(int initialCapacity, 
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信