作者:炸鸡可乐

原文出处:www.pzblog.cn

一、摘要

在集合系列的第一章,咱们了解到,Map的实现类有HashMap、LinkedHashMap、TreeMap、IdentityHashMap、WeakHashMap、Hashtable、Properties等等。

本文主要从数据结构和算法层面,探讨LinkedHashMap的实现。

二、简介

LinkedHashMap可以认为是HashMap+LinkedList,它既使用HashMap操作数据结构,又使用LinkedList维护插入元素的先后顺序,内部采用双向链表(doubly-linked list)的形式将所有元素( entry )连接起来。

LinkedHashMap继承了HashMap,允许放入key为null的元素,也允许插入value为null的元素。从名字上可以看出该容器是LinkedList和HashMap的混合体,也就是说它同时满足HashMap和LinkedList的某些特性,可将LinkedHashMap看作采用Linked list增强的HashMap。

打开 LinkedHashMap 源码,可以看到主要三个核心属性:

  1. public class LinkedHashMap<K,V>
  2. extends HashMap<K,V>
  3. implements Map<K,V>{
  4. /**双向链表的头节点*/
  5. transient LinkedHashMap.Entry<K,V> head;
  6. /**双向链表的尾节点*/
  7. transient LinkedHashMap.Entry<K,V> tail;
  8. /**
  9. * 1、如果accessOrder为true的话,则会把访问过的元素放在链表后面,放置顺序是访问的顺序
  10. * 2、如果accessOrder为false的话,则按插入顺序来遍历
  11. */
  12. final boolean accessOrder;
  13. }

LinkedHashMap 在初始化阶段,默认按插入顺序来遍历

  1. public LinkedHashMap() {
  2. super();
  3. accessOrder = false;
  4. }

LinkedHashMap 采用的 Hash 算法和 HashMap 相同,不同的是,它重新定义了数组中保存的元素Entry,该Entry除了保存当前对象的引用外,还保存了其上一个元素before和下一个元素after的引用,从而在哈希表的基础上又构成了双向链接列表。

源码如下:

  1. static class Entry<K,V> extends HashMap.Node<K,V> {
  2. //before指的是链表前驱节点,after指的是链表后驱节点
  3. Entry<K,V> before, after;
  4. Entry(int hash, K key, V value, Node<K,V> next) {
  5. super(hash, key, value, next);
  6. }
  7. }

可以直观的看出,双向链表头部插入的数据为链表的入口,迭代器遍历方向是从链表的头部开始到链表尾部结束。

除了可以保迭代历顺序,这种结构还有一个好处:迭代LinkedHashMap时不需要像HashMap那样遍历整个table,而只需要直接遍历header指向的双向链表即可,也就是说LinkedHashMap的迭代时间就只跟entry的个数相关,而跟table的大小无关。

三、常用方法介绍

3.1、get方法

get方法根据指定的key值返回对应的value。该方法跟HashMap.get()方法的流程几乎完全一样,默认按照插入顺序遍历。

  1. public V get(Object key) {
  2. Node<K,V> e;
  3. if ((e = getNode(hash(key), key)) == null)
  4. return null;
  5. if (accessOrder)
  6. afterNodeAccess(e);
  7. return e.value;
  8. }

如果accessOrdertrue的话,会把访问过的元素放在链表后面,放置顺序是访问的顺序

  1. void afterNodeAccess(Node<K,V> e) { // move node to last
  2. LinkedHashMap.Entry<K,V> last;
  3. if (accessOrder && (last = tail) != e) {
  4. LinkedHashMap.Entry<K,V> p =
  5. (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
  6. p.after = null;
  7. if (b == null)
  8. head = a;
  9. else
  10. b.after = a;
  11. if (a != null)
  12. a.before = b;
  13. else
  14. last = b;
  15. if (last == null)
  16. head = p;
  17. else {
  18. p.before = last;
  19. last.after = p;
  20. }
  21. tail = p;
  22. ++modCount;
  23. }
  24. }

测试用例:

  1. public static void main(String[] args) {
  2. //accessOrder默认为false
  3. Map<String, String> accessOrderFalse = new LinkedHashMap<>();
  4. accessOrderFalse.put("1","1");
  5. accessOrderFalse.put("2","2");
  6. accessOrderFalse.put("3","3");
  7. accessOrderFalse.put("4","4");
  8. System.out.println("acessOrderFalse:"+accessOrderFalse.toString());
  9. //accessOrder设置为true
  10. Map<String, String> accessOrderTrue = new LinkedHashMap<>(16, 0.75f, true);
  11. accessOrderTrue.put("1","1");
  12. accessOrderTrue.put("2","2");
  13. accessOrderTrue.put("3","3");
  14. accessOrderTrue.put("4","4");
  15. accessOrderTrue.get("2");//获取键2
  16. accessOrderTrue.get("3");//获取键3
  17. System.out.println("accessOrderTrue:"+accessOrderTrue.toString());
  18. }

输出结果:

  1. acessOrderFalse:{1=1, 2=2, 3=3, 4=4}
  2. accessOrderTrue:{1=1, 4=4, 2=2, 3=3}

3.2、put方法

put(K key, V value)方法是将指定的key, value对添加到map里。该方法首先会调用HashMap的插入方法,同样对map做一次查找,看是否包含该元素,如果已经包含则直接返回,查找过程类似于get()方法;如果没有找到,将元素插入集合。

  1. /**HashMap 中实现*/
  2. public V put(K key, V value) {
  3. return putVal(hash(key), key, value, false, true);
  4. }
  5. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  6. boolean evict) {
  7. Node<K,V>[] tab; Node<K,V> p; int n, i;
  8. if ((tab = table) == null || (n = tab.length) == 0)
  9. n = (tab = resize()).length;
  10. if ((p = tab[i = (n - 1) & hash]) == null)
  11. tab[i] = newNode(hash, key, value, null);
  12. else {
  13. Node<K,V> e; K k;
  14. if (p.hash == hash &&
  15. ((k = p.key) == key || (key != null && key.equals(k))))
  16. e = p;
  17. else if (p instanceof TreeNode)
  18. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  19. else {
  20. for (int binCount = 0; ; ++binCount) {
  21. if ((e = p.next) == null) {
  22. p.next = newNode(hash, key, value, null);
  23. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  24. treeifyBin(tab, hash);
  25. break;
  26. }
  27. if (e.hash == hash &&
  28. ((k = e.key) == key || (key != null && key.equals(k))))
  29. break;
  30. p = e;
  31. }
  32. }
  33. if (e != null) { // existing mapping for key
  34. V oldValue = e.value;
  35. if (!onlyIfAbsent || oldValue == null)
  36. e.value = value;
  37. afterNodeAccess(e);
  38. return oldValue;
  39. }
  40. }
  41. ++modCount;
  42. if (++size > threshold)
  43. resize();
  44. afterNodeInsertion(evict);
  45. return null;
  46. }

LinkedHashMap 中覆写的方法

  1. // LinkedHashMap 中覆写
  2. Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
  3. LinkedHashMap.Entry<K,V> p =
  4. new LinkedHashMap.Entry<K,V>(hash, key, value, e);
  5. // 将 Entry 接在双向链表的尾部
  6. linkNodeLast(p);
  7. return p;
  8. }
  9. private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
  10. LinkedHashMap.Entry<K,V> last = tail;
  11. tail = p;
  12. // last 为 null,表明链表还未建立
  13. if (last == null)
  14. head = p;
  15. else {
  16. // 将新节点 p 接在链表尾部
  17. p.before = last;
  18. last.after = p;
  19. }
  20. }

3.3、remove方法

remove(Object key)的作用是删除key值对应的entry,该方法实现逻辑主要以HashMap为主,首先找到key值对应的entry,然后删除该entry(修改链表的相应引用),查找过程跟get()方法类似,最后会调用 LinkedHashMap 中覆写的方法,将其删除!

  1. /**HashMap 中实现*/
  2. public V remove(Object key) {
  3. Node<K,V> e;
  4. return (e = removeNode(hash(key), key, null, false, true)) == null ?
  5. null : e.value;
  6. }
  7. final Node<K,V> removeNode(int hash, Object key, Object value,
  8. boolean matchValue, boolean movable) {
  9. Node<K,V>[] tab; Node<K,V> p; int n, index;
  10. if ((tab = table) != null && (n = tab.length) > 0 &&
  11. (p = tab[index = (n - 1) & hash]) != null) {
  12. Node<K,V> node = null, e; K k; V v;
  13. if (p.hash == hash &&
  14. ((k = p.key) == key || (key != null && key.equals(k))))
  15. node = p;
  16. else if ((e = p.next) != null) {
  17. if (p instanceof TreeNode) {...}
  18. else {
  19. // 遍历单链表,寻找要删除的节点,并赋值给 node 变量
  20. do {
  21. if (e.hash == hash &&
  22. ((k = e.key) == key ||
  23. (key != null && key.equals(k)))) {
  24. node = e;
  25. break;
  26. }
  27. p = e;
  28. } while ((e = e.next) != null);
  29. }
  30. }
  31. if (node != null && (!matchValue || (v = node.value) == value ||
  32. (value != null && value.equals(v)))) {
  33. if (node instanceof TreeNode) {...}
  34. // 将要删除的节点从单链表中移除
  35. else if (node == p)
  36. tab[index] = node.next;
  37. else
  38. p.next = node.next;
  39. ++modCount;
  40. --size;
  41. afterNodeRemoval(node); // 调用删除回调方法进行后续操作
  42. return node;
  43. }
  44. }
  45. return null;
  46. }

LinkedHashMap 中覆写的 afterNodeRemoval 方法

  1. void afterNodeRemoval(Node<K,V> e) { // unlink
  2. LinkedHashMap.Entry<K,V> p =
  3. (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
  4. // 将 p 节点的前驱后后继引用置空
  5. p.before = p.after = null;
  6. // b 为 null,表明 p 是头节点
  7. if (b == null)
  8. head = a;
  9. else
  10. b.after = a;
  11. // a 为 null,表明 p 是尾节点
  12. if (a == null)
  13. tail = b;
  14. else
  15. a.before = b;
  16. }

四、总结

LinkedHashMap 继承自 HashMap,所有大部分功能特性基本相同,二者唯一的区别是 LinkedHashMap 在HashMap的基础上,采用双向链表(doubly-linked list)的形式将所有 entry 连接起来,这样是为保证元素的迭代顺序跟插入顺序相同。

主体部分跟HashMap完全一样,多了header指向双向链表的头部,tail指向双向链表的尾部,默认双向链表的迭代顺序就是entry的插入顺序。

五、参考

1、JDK1.7&JDK1.8 源码

2、博客园 - CarpenterLee - Java集合框架源码剖析LinkedHashMap

【集合系列】- 深入浅出分析LinkedHashMap的更多相关文章

  1. 【Java集合系列六】LinkedHashMap解析

    2017-08-14 16:30:10 1.简介 LinkedHashMap继承自HashMap,能保证迭代顺序,支持其他Map可选的操作.采用双向链表存储元素,默认的迭代序是插入序.重复插入一个已经 ...

  2. 【集合系列】- 深入浅出的分析 Set集合

    一.摘要 关于 Set 接口,在实际开发中,其实很少用到,但是如果你出去面试,它可能依然是一个绕不开的话题. 言归正传,废话咱们也不多说了,相信使用过 Set 集合类的朋友都知道,Set集合的特点主要 ...

  3. 【Java集合系列】目录

    2017-07-29 13:49:40 一.Collection的全局继承关系 二.系列文章 [Java集合系列一]ArrayList解析 备注: 1.ArrayList本质上就是一个数组,所有对外提 ...

  4. Java集合系列[4]----LinkedHashMap源码分析

    这篇文章我们开始分析LinkedHashMap的源码,LinkedHashMap继承了HashMap,也就是说LinkedHashMap是在HashMap的基础上扩展而来的,因此在看LinkedHas ...

  5. 【集合系列】- 深入浅出的分析TreeMap

    一.摘要 在集合系列的第一章,咱们了解到,Map的实现类有HashMap.LinkedHashMap.TreeMap.IdentityHashMap.WeakHashMap.Hashtable.Pro ...

  6. 【集合系列】- 深入浅出的分析 Hashtable

    一.摘要 在集合系列的第一章,咱们了解到,Map 的实现类有 HashMap.LinkedHashMap.TreeMap.IdentityHashMap.WeakHashMap.Hashtable.P ...

  7. 【集合系列】- 深入浅出分析HashMap

    一.摘要 在集合系列的第一章,咱们了解到,Map的实现类有HashMap.LinkedHashMap.TreeMap.IdentityHashMap.WeakHashMap.Hashtable.Pro ...

  8. 【集合系列】- 深入浅出的分析IdentityHashMap

    一.摘要 在集合系列的第一章,咱们了解到,Map 的实现类有 HashMap.LinkedHashMap.TreeMap.IdentityHashMap.WeakHashMap.Hashtable.P ...

  9. 【集合系列】- 深入浅出的分析 WeakHashMap

    一.摘要 在集合系列的第一章,咱们了解到,Map 的实现类有 HashMap.LinkedHashMap.TreeMap.IdentityHashMap.WeakHashMap.Hashtable.P ...

随机推荐

  1. .NET Core API后台架构搭建

    ASP.NET Core API后台架构搭建 项目文件:https://files.cnblogs.com/files/ZM191018/WebAPI.zip 本篇可以了解到: 依赖注入 Dapper ...

  2. Web安全之注入点构造

    在测试过程中,经常需要自己本地构造注入点来进行SQL测试,这边分享一下,不同环境下构造SQL注入的代码. PHP+MYSQL版 <?php $con = mysql_connect(" ...

  3. Neo4j:图数据库GraphDB(二)高级查找

    接着上一篇,继续介绍图数据库Neo4j: http://www.cnblogs.com/rongyux/p/5537028.html 三 高级查找操作 1过滤   name = "Tom H ...

  4. VSCode 配置 Python 开发环境

    一.环境准备 首先需要先安装好 Python 和 VSCode, 下载地址如下 VSCode Python 二.安装 Python 扩展 首先在VSCode上安装 Python 扩展,如图: 三.新建 ...

  5. 自定义的Spring Boot starter如何设置自动配置注解

    本文首发于个人网站: 在Spring Boot实战之定制自己的starter一文最后提到,触发Spring Boot的配置过程有两种方法: spring.factories:由Spring Boot触 ...

  6. Js极客之路 - 简化操作

    1.对字符串使用单引号(避免动态添加元素时html会出现的双引号"引起的冲突,方便操作 - 单引号一个键,双引号两个键) // bad var name = "Barrior&qu ...

  7. ArcGIS Engine专题地图渲染器的实现(入门版)

    专题地图(Thematic Map)是着重表示一种或数种自然要素特征或社会经济现象的地图 专题地图的内容由两部分构成: 1.专题内容——图上突出表示的自然或社会经济现象及其有关特征 2.地理基础——用 ...

  8. Java面试题---基础篇

    经常阅读一些牛人的基础博以及相关个人经历,你才发现自己真的不够努力,人生路漫漫,希望本人以及看客能走出一条自己不后悔的人生路,骚年  加油!!! 回归正题 一  java基础知识点 1)java面向对 ...

  9. Spring Cloud Alibaba(三)Sentinel之熔断降级

    本项目演示如何使用 Sentinel 完成 Spring Cloud 应用的熔断降级调用. Sentinel 是阿里巴巴开源的分布式系统的流量防卫组件,Sentinel 把流量作为切入点,从流量控制, ...

  10. 微信公众号 访问403问题,样式错乱,js失效

    我服了,还是那个微信公众号小项目. 这个项目用的是ssm+velocity 问题的是,有时候页面加载会乱,js,css都加载不出来. 这个问题也是很久了,前几天开会,那个甲方医院很不开心,说是要找下家 ...