当前位置:编程学习 > JAVA >>

LinkedHashMap源码浅析

 

此系列文章中,上一篇是关于HashMap的源码剖析,这篇文章将向大家剖析一下LinkedHashMap的源码!

 

四. LinkedHashMap

 

我们知道从API的描述中可以看出HashMap与LinkedHashMap最大的不同在于,后者维护者一个运行于所有条目的双向链表。有了这个双向链表,就可以在迭代的时候按照插入的顺序迭代出元素(当然也可以通过LRU算法迭代元素,下面会讲到)。

 

1. 类结构

Java代码 

public class LinkedHashMap<K, V> extends HashMap<K, V> implements Map<K, V> 

 

我们可以看出LinkedHashMap继承了HashMap!

 

2. 几个重要的成员变量

Java代码 

/**                                                                     

 * The head of the doubly linked list.                                   

 */                                                                      

private transient Entry<K, V> header;                                    

                                                                         

/**                                                                      

 * The iteration ordering method for this linked hash map: <tt>true</tt>

 * for access-order, <tt>false</tt> for insertion-order.                

 *                                                                       

 * @serial                                                              

 */                                                                      

private final boolean accessOrder;                                        

 

 对于父类HashMap中的成员变量这里就不讲了,可参考http://boy00fly.iteye.com/blog/1139845

 其中Entry类是LinkedHashMap的内部类定义,代码片段如下:

Java代码 

//继承了HashMap.Entry                                        

private static class Entry<K, V> extends HashMap.Entry<K, V> 

//新增的两个成员变量                                          

Entry<K, V> before, after;                                   

 

 可以看得出来新增的这两个变量就是双向链表实现的关键!!分别指向当前Entry的前一个、后一个Entry。

 

header就是指向双向链表的头部!

accessOrder:true则按照LRU算法迭代整个LinkedHashMap,false则按照元素的插入顺序迭代!

 

3. 几个重要的构造函数

Java代码 

/**

  * Constructs an empty <tt>LinkedHashMap</tt> instance with the

  * specified initial capacity, load factor and ordering mode.

  *

  * @param  initialCapacity the initial capacity

  * @param  loadFactor      the load factor

  * @param  accessOrder     the ordering mode - <tt>true</tt> for

  *         access-order, <tt>false</tt> for insertion-order

  * @throws IllegalArgumentException if the initial capacity is negative

  *         or the load factor is nonpositive

  */  

 public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) 

 { 

     super(initialCapacity, loadFactor); 

     this.accessOrder = accessOrder; 

 } 

    是不是很简单,也可参考http://boy00fly.iteye.com/blog/1139845这篇文章的构造函数分析。其中accessOrder就是我们上面所讲的控制迭代顺序的开关,只有此构造函数有这个参数,其他的构造函数默认就是false。

 

4. 几个重要的方法

Java代码 

/**

  * Called by superclass constructors and pseudoconstructors (clone,

  * readObject) before any entries are inserted into the map.  Initializes

  * the chain.

  */ 

 void init() 

 { 

     header = new Entry<K,

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,