LinkedHashMap

LinkedHashMap内部採用了散列表和链表实现Map接口,并能够保证迭代的顺序,和HashMap不同,其内部维护一个指向全部元素的双向链表,其决定了遍历的顺序,一般是元素插入的顺序进行迭代,只是元素又一次插入顺序不会受到影响。

LinkedHashMap提供一个特殊的构造函数,实现了每次迭代返回近期使用的元素,这个特性能够用于构建LRU缓存。

此外removeEldestEntry(Map.Entry)方法能够被子类覆盖用于推断在加入元素的时候什么时候能够删除元素。

LinkedHashMap性能相同受到初始容量和装填因子的影响,对于基本操作(add,contains,remove)在常数时间内,其性能比HashMap略微低。因为须要额外代价维护链表;只是其遍历性能为O(size)高于HashMapO(capacity)。

LinkedHashMap实现

类定义

直接继承了HashMap

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

成员

private transient Entry<K,V> header; //用于遍历的双向链表表头

/**
* The iteration ordering method for this linked hash map:
* true: for access-order, false: for insertion-order
*/
private final boolean accessOrder;

Entry内部类继承了HashMap.Entry<K,V>类,添加了两个指针before和after用于维护遍历顺序,实际上Entry有三个指针父类本身有个next指针用于当发生元素冲突时指向的下一个元素。

由此能够看出用于遍历的双向链表直接加在Entry上面,这样有效节约了空间,实际仅仅比HashMap多了2*size个引用+1个头结点空间消耗。

before和after这两个引用在外部类调用put或remove时,调用其相关方法进行维护(recordAccess和recordRemoval等)。

 private static class Entry<K,V> extends HashMap.Entry<K,V> {
Entry<K,V> before, after; Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
super(hash, key, value, next);
} private void remove() {
before.after = after;
after.before = before;
}
//existingEntry之前加入当前节点
private void addBefore(Entry<K,V> existingEntry) {
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
}
//由父类HashMap的put方法调用,若是acessOrder。则加入到双向链表的头结点后面;本身get方法也会触发调用
void recordAccess(HashMap<K,V> m) {
LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
if (lm.accessOrder) {
lm.modCount++;
remove();
addBefore(lm.header);
}
}
//有元素删除时,调用该方法
void recordRemoval(HashMap<K,V> m) {
remove();
}
}

put方法是继承自父类HashMap,重写了当须要加入元素时候调用的addEntry方法,相同是在相应桶的链表头结点后面加入。加入完以后不是直接进行resize推断,而是推断是否要删除旧的元素,这种方法默认返回false,用户能够重写这种方法用于确定缓存的淘汰机制。

void addEntry(int hash, K key, V value, int bucketIndex) {
createEntry(hash, key, value, bucketIndex); // Remove eldest entry if instructed, else grow capacity if appropriate
Entry<K,V> eldest = header.after;
if (removeEldestEntry(eldest)) {
removeEntryForKey(eldest.key);
} else {
if (size >= threshold)
resize(2 * table.length);
}
} void createEntry(int hash, K key, V value, int bucketIndex) {
HashMap.Entry<K,V> old = table[bucketIndex];
Entry<K,V> e = new Entry<K,V>(hash, key, value, old);
table[bucketIndex] = e;
e.addBefore(header); //每次都是在相应桶链表的開始处加入
size++;
} protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return false;
}

get方法

public V get(Object key) {
Entry<K,V> e = (Entry<K,V>)getEntry(key);
if (e == null)
return null;
e.recordAccess(this); //实现LRU
return e.value;
}
//重写父类方法,效率更高O(size)
public boolean containsValue(Object value) {
// Overridden to take advantage of faster iterator
if (value==null) {
for (Entry e = header.after; e != header; e = e.after)
if (e.value==null)
return true;
} else {
for (Entry e = header.after; e != header; e = e.after)
if (value.equals(e.value))
return true;
}
return false;
}

视图和迭代器

LinkedHashMap相同继承了创建3个集合类视图:键集合、值集合、键值对集合的方法。因为额外维护一个双向链表保证迭代顺序,重写了相关视图的迭代器实现,LinkedHashIterator通过直接迭代链表的header指针来实现指定顺序遍历。

Iterator<K> newKeyIterator()   { return new KeyIterator();   }
Iterator<V> newValueIterator() { return new ValueIterator(); }
Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); } private class KeyIterator extends LinkedHashIterator<K> {
public K next() { return nextEntry().getKey(); }
} private class ValueIterator extends LinkedHashIterator<V> {
public V next() { return nextEntry().value; }
} private class EntryIterator extends LinkedHashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() { return nextEntry(); }
} private abstract class LinkedHashIterator<T> implements Iterator<T> {
Entry<K,V> nextEntry = header.after;
Entry<K,V> lastReturned = null;
int expectedModCount = modCount; public boolean hasNext() {
return nextEntry != header;
} public void remove() {
if (lastReturned == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException(); LinkedHashMap.this.remove(lastReturned.key);
lastReturned = null;
expectedModCount = modCount;
} Entry<K,V> nextEntry() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (nextEntry == header)
throw new NoSuchElementException(); Entry<K,V> e = lastReturned = nextEntry;
nextEntry = e.after;
return e;
}
}

总结

  1. LinkedHashMap继承自HashMap。相关基本操作性能略低于HashMap。因为须要额外代价维护链表。其遍历操作是通过操作该双向链表实现,而非内部散列表数组。因此性能为O(size)比HashMapO(capacity)更高。
  2. 支持两种顺序遍历:元素插入顺序(反复put不算)和近期使用优先顺序(调用put和get类似LRU),默认是依照元素插入顺序遍历。通过构造函数传入true能够实现近期使用优先遍历。每次put或get操作时,将该元素直接又一次放置到链表头结点后面来实现近期使用优先遍历。

  3. LinkedHashMap并没有又一次创建一个新的链表来实现顺序遍历,而是在每一个Entry上多加了两个指针来决定遍历顺序。有效节约了空间消耗。

    实际仅仅比HashMap多了2*size个引用+1个头结点空间消耗。

  4. LinkedHashMap支持元素淘汰策略,能够通过重写removeEldestEntry方法。来决定调用put时候是否须要删除旧的元素。LinkedHashMap能够用于实现LRU缓存,并自己定义元素淘汰策略。

LinkedHashMap源代码阅读的更多相关文章

  1. Mongodb源代码阅读笔记:Journal机制

    Mongodb源代码阅读笔记:Journal机制 Mongodb源代码阅读笔记:Journal机制 涉及的文件 一些说明 PREPLOGBUFFER WRITETOJOURNAL WRITETODAT ...

  2. 【转】Tomcat总体结构(Tomcat源代码阅读系列之二)

    本文是Tomcat源代码阅读系列的第二篇文章,我们在本系列的第一篇文章:在IntelliJ IDEA 和 Eclipse运行tomcat 7源代码一文中介绍了如何在intelliJ IDEA 和 Ec ...

  3. 利用doxygen提高源代码阅读效率

    阅读开源项目的源代码是提高自己编程能力的好方法,而有一个好的源代码阅读工具无疑能够让你在阅读源代码时事半功倍.之前找过不少源代码阅读工具,像SourceInsight.sourcenav.scitoo ...

  4. CI框架源代码阅读笔记5 基准測试 BenchMark.php

    上一篇博客(CI框架源代码阅读笔记4 引导文件CodeIgniter.php)中.我们已经看到:CI中核心流程的核心功能都是由不同的组件来完毕的.这些组件类似于一个一个单独的模块,不同的模块完毕不同的 ...

  5. 淘宝数据库OceanBase SQL编译器部分 源代码阅读--Schema模式

    淘宝数据库OceanBase SQL编译器部分 源代码阅读--Schema模式 什么是Database,什么是Schema,什么是Table,什么是列,什么是行,什么是User?我们能够能够把Data ...

  6. CI框架源代码阅读笔记3 全局函数Common.php

    从本篇開始.将深入CI框架的内部.一步步去探索这个框架的实现.结构和设计. Common.php文件定义了一系列的全局函数(一般来说.全局函数具有最高的载入优先权.因此大多数的框架中BootStrap ...

  7. [C++ 2011 STL (VS2012 Update4) 源代码阅读系列(2)]熟悉一些宏定义和模版偏特化或叫模版专门化

    [C++ 2011 STL (VS2012 Update4) 源代码阅读系列(2)]熟悉一些宏定义和模版偏特化或叫模版专门化 // point_test.cpp : 知识点练习和测试,用于单步调试,跟 ...

  8. 【转】Tomcat源代码阅读系列

    在IntelliJ IDEA 和 Eclipse运行tomcat 7源代码(Tomcat源代码阅读系列之一) Tomcat总体结构(Tomcat源代码阅读系列之二) Tomcat启动过程(Tomcat ...

  9. 【Java集合源代码剖析】LinkedHashmap源代码剖析

    转载请注明出处:http://blog.csdn.net/ns_code/article/details/37867985 前言:有网友建议分析下LinkedHashMap的源代码.于是花了一晚上时间 ...

随机推荐

  1. linux上搭建svn

    参照网址:http://www.cnblogs.com/LusYoHo/p/6056377.html(如何在linux下搭建svn服务)                http://www.cnblo ...

  2. NHibernate系列学习(二)-使用sql和hql以及linq

    1.本文主要介绍了NH的三种查询方式 2.界面查看 3.代码架构 4.代码详情 namespace KimismeDemo { public partial class Form2 : Form { ...

  3. python自动化测试框架(一)

    1.开发环境 名称 版本 系统 windows 7 python版本 2.7.14 IDE pycharm2017 2.大致框架流程 :展示了框架实现的业务流程 3.框架介绍 3.1 ======完善 ...

  4. 挂载硬盘,提示 mount: unknown filesystem type 'LVM2_member'的解决方案

    问题现象:由于重装linux,并且加了固态硬盘,直接将系统装在固态硬盘中.启动服务器的时候, 便看不到原来机械硬盘的挂载目录了,不知如何访问机械硬盘了.直接用命令 mount /dev/sda3 /s ...

  5. Windows下环境变量显示、设置或删除操作详情

    显示.设置或删除 cmd.exe 环境变量. SET [variable=[string]] variable 指定环境变量名. string 指定要指派给变量的一系列字符串. 要显示当前环境变量,键 ...

  6. THREE.DecalGeometry(转载)

    function getDecalGeometry(position, direction){ var decalGeometry = new THREE.DecalGeometry( earthMe ...

  7. 【技术累积】【点】【java】【26】@Value默认值

    @Value 该注解可以把配置文件中的值赋给属性 @Value("${shit.config}") private String shit; 要在xml文件中设置扫描包+place ...

  8. Lazarus Reading XML- with TXMLDocument and TXPathVariable

    也就是使用XPath的方式,具体语法规则查看http://www.w3school.com.cn/xpath/xpath_syntax.asp,说明得相当详细.这里列举例子是说明在Lazarus/FP ...

  9. Centos6.7 ELK日志系统部署

    Centos6.7 ELK日志系统部署 原文地址:http://www.cnblogs.com/caoguo/p/4991602.html 一. 环境 elk服务器:192.168.55.134 lo ...

  10. https Full Handshake

    1)加密套件交互: 2)密码交换: 3)身份认证: Full Handshake Initially, client and server "agree upon" null en ...