众所周知 HashMap 是一个无序的 Map,因为每次根据 keyhashcode 映射到 Entry 数组上,所以遍历出来的顺序并不是写入的顺序。

因此 JDK 推出一个基于 HashMap 但具有顺序的 LinkedHashMap 来解决有排序需求的场景。

它的底层是继承于 HashMap 实现的,由一个双向链表所构成。

LinkedHashMap 的排序方式有两种:

  • 根据写入顺序排序。
  • 根据访问顺序排序。

其中根据访问顺序排序时,每次 get 都会将访问的值移动到链表末尾,这样重复操作就能的到一个按照访问顺序排序的链表。

数据结构

	@Test
public void test(){
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("1",1) ;
map.put("2",2) ;
map.put("3",3) ;
map.put("4",4) ;
map.put("5",5) ;
System.out.println(map.toString()); }

调试可以看到 map 的组成:

打开源码可以看到:

    /**
* 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; private static class Entry<K,V> extends HashMap.Entry<K,V> {
// These fields comprise the doubly linked list used for iteration.
Entry<K,V> before, after; Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
super(hash, key, value, next);
}
}

其中 Entry 继承于 HashMapEntry,并新增了上下节点的指针,也就形成了双向链表。

还有一个 header 的成员变量,是这个双向链表的头结点。

上边的 demo 总结成一张图如下:

第一个类似于 HashMap 的结构,利用 Entry 中的 next 指针进行关联。

下边则是 LinkedHashMap 如何达到有序的关键。

就是利用了头节点和其余的各个节点之间通过 Entry 中的 afterbefore 指针进行关联。

其中还有一个 accessOrder 成员变量,默认是 false,默认按照插入顺序排序,为 true 时按照访问顺序排序,也可以调用:

    public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}

这个构造方法可以显示的传入 accessOrder

构造方法

LinkedHashMap 的构造方法:

    public LinkedHashMap() {
super();
accessOrder = false;
}

其实就是调用的 HashMap 的构造方法:

HashMap 实现:

    public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor); this.loadFactor = loadFactor;
threshold = initialCapacity;
//HashMap 只是定义了改方法,具体实现交给了 LinkedHashMap
init();
}

可以看到里面有一个空的 init(),具体是由 LinkedHashMap 来实现的:

    @Override
void init() {
header = new Entry<>(-1, null, null, null);
header.before = header.after = header;
}

其实也就是对 header 进行了初始化。

put 方法

LinkedHashMapput() 方法之前先看看 HashMapput 方法:

    public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
//空实现,交给 LinkedHashMap 自己实现
e.recordAccess(this);
return oldValue;
}
} modCount++;
// LinkedHashMap 对其重写
addEntry(hash, key, value, i);
return null;
} // LinkedHashMap 对其重写
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
} createEntry(hash, key, value, bucketIndex);
} // LinkedHashMap 对其重写
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}

主体的实现都是借助于 HashMap 来完成的,只是对其中的 recordAccess(), addEntry(), createEntry() 进行了重写。

LinkedHashMap 的实现:

        //就是判断是否是根据访问顺序排序,如果是则需要将当前这个 Entry 移动到链表的末尾
void recordAccess(HashMap<K,V> m) {
LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
if (lm.accessOrder) {
lm.modCount++;
remove();
addBefore(lm.header);
}
} //调用了 HashMap 的实现,并判断是否需要删除最少使用的 Entry(默认不删除)
void addEntry(int hash, K key, V value, int bucketIndex) {
super.addEntry(hash, key, value, bucketIndex); // Remove eldest entry if instructed
Entry<K,V> eldest = header.after;
if (removeEldestEntry(eldest)) {
removeEntryForKey(eldest.key);
}
} void createEntry(int hash, K key, V value, int bucketIndex) {
HashMap.Entry<K,V> old = table[bucketIndex];
Entry<K,V> e = new Entry<>(hash, key, value, old);
//就多了这一步,将新增的 Entry 加入到 header 双向链表中
table[bucketIndex] = e;
e.addBefore(header);
size++;
} //写入到双向链表中
private void addBefore(Entry<K,V> existingEntry) {
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
}

get 方法

LinkedHashMap 的 get() 方法也重写了:

    public V get(Object key) {
Entry<K,V> e = (Entry<K,V>)getEntry(key);
if (e == null)
return null; //多了一个判断是否是按照访问顺序排序,是则将当前的 Entry 移动到链表头部。
e.recordAccess(this);
return e.value;
} void recordAccess(HashMap<K,V> m) {
LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
if (lm.accessOrder) {
lm.modCount++; //删除
remove();
//添加到头部
addBefore(lm.header);
}
}

clear() 清空就要比较简单了:

    //只需要把指针都指向自己即可,原本那些 Entry 没有引用之后就会被 JVM 自动回收。
public void clear() {
super.clear();
header.before = header.after = header;
}

总结

总的来说 LinkedHashMap 其实就是对 HashMap 进行了拓展,使用了双向链表来保证了顺序性。

因为是继承与 HashMap 的,所以一些 HashMap 存在的问题 LinkedHashMap 也会存在,比如不支持并发等。

号外

最近在总结一些 Java 相关的知识点,感兴趣的朋友可以一起维护。

地址: https://github.com/crossoverJie/Java-Interview

LinkedHashMap 底层分析的更多相关文章

  1. HDFS下载数据机制的底层分析

    HDFS下载数据机制的底层分析 Hadoop中的RPC(Remote Procedure Call)框架 hadoop中结点间的通信采用的是RPC. RPC框架的实现机制图解: 从hdfs下载数据的源 ...

  2. HashMap底层分析

    以下基于 JDK1.7 分析. 如图所示,HashMap 底层是基于数组和链表实现的.其中有两个重要的参数: 容量 负载因子 容量的默认大小是 16,负载因子是 0.75,当 HashMap 的 si ...

  3. Block详解二(底层分析)

    Block专辑: Block讲解一 MRC-block与ARC-block Block详解一(底层分析) 今天讲述Block的最后一篇,后两篇仅仅是加深1,2篇的理解,废话少说,开始讲解! __blo ...

  4. JDK1.8源码逐字逐句带你理解LinkedHashMap底层

    注意 我希望看这篇的文章的小伙伴如果没有了解过HashMap那么可以先看看我这篇文章:http://blog.csdn.net/u012403290/article/details/65442646, ...

  5. hashMap 底层原理+LinkedHashMap 底层原理+常见面试题

    1.源码 java1.7    hashMap 底层实现是数组+链表 java1.8 对上面进行优化  数组+链表+红黑树 2.hashmap  是怎么保存数据的. 在hashmap 中有这样一个结构 ...

  6. HashMap 底层分析

    以下基于 JDK1.7 分析 如图所示,HashMap底层是基于数组和链表实现的,其中有两个重要的参数: ---容量 ---负载因子 容量的默认大小是16,负载因子是0.75,当HashMap的siz ...

  7. 5.4 集合的排序(Java学习笔记)(Collections.sort(),及Arrays.sort()底层分析)

    1.Comparable接口 这个接口顾名思义就是用于排序的,如果要对某些对象进行排序,那么该对象所在的类必须实现 Comparabld接口.Comparable接口只有一个方法CompareTo() ...

  8. Swift--struct与class的区别(汇编角度底层分析)

    概述 相对Objective-C, Swift使用结构体Struct的比例大大增加了,其中Int, Bool,以及String,Array等底层全部使用Struct来定义!在Swift中结构体不仅可以 ...

  9. Java类集框架详细汇总-底层分析

    前言: Java的类集框架比较多,也十分重要,在这里给出图解,可以理解为相应的继承关系,也可以当作重要知识点回顾: Collection集合接口 继承自:Iterable public interfa ...

随机推荐

  1. org.springframework.web.context.ContextLoaderListener 解决方案

    tomcat启动项目报错,没找到这个类 我直接下了一个spring-web-4.3.8.RELEASE.jar 的 jar 包方到web-inf目录下.问题解决. 补充: 如果在检查了项目 jar 环 ...

  2. RabbitMQ中RPC的实现及其通信机制

    RabbitMQ中RPC的实现:客户端发送请求消息,服务端回复响应消息,为了接受响应response,客户端需要发送一个回调队列的地址来接受响应,每条消息在发送的时候会带上一个唯一的correlati ...

  3. mybatis中有趣的符号#与$

    ${ }是字符串替换,相当于直接显示数据,#{ }是预编译处理,相当于对数据加上双引号 即#是将传入的值当做字符串的形式,先替换为?号,然后调用PreparedStatement的set方法来赋值,而 ...

  4. CF987B - High School: Become Human

    Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But ...

  5. 最短路径---dijkstra算法模板

    dijkstra算法模板 http://acm.hdu.edu.cn/showproblem.php?pid=1874 #include<stdio.h> #include<stri ...

  6. 【转】window.onerror跨域问题

    What the heck is "Script error"? Ben Vinegar/ May 17, 2016 If you’ve done any work with th ...

  7. hcna(华为)_Telnet篇

    Telnet提供了一个交互式操作界面,允许终端远程登录到任何可以充当 Telnet服务器的设备.Telnet用户可以像通过Console口本地登录一样对 设备进行操作.远端Telnet服务器和终端之间 ...

  8. 读《31天学会CRM项目开发》记录4 - WEB服务配置

    好几天没有更新记录了,因为最近都在看本书的基础内容,然后跟着练习.等看到数据库部分,就晕菜了,只能草草浏览一遍,想在后面的实战中再加强. 下面是对IIS 和ASP.NET的配置! 一.什么是IIS? ...

  9. RSP小组——团队冲刺博客六

    RSP小组--团队冲刺博客六 冲刺日期:2018年12月18日 前言 各成员今日(12.18)完成的任务 李闻洲,赵乾宸代码合并 马瑞蕃图形后续支持,编写博客,燃尽图 蒋子行会议记录 各个成员的任务安 ...

  10. 编程菜鸟的日记-初学尝试编程-C++ Primer Plus 第6章编程练习4

    #include <iostream> using namespace std; const int strsize=30; const int BOPSIZE=5; void showm ...