java Linkedhashmap源码分析
LinkedHashMap类似于HashMap,但是迭代遍历它时,取得“键值对”的顺序是插入次序,或者是最近最少使用(LRU)的次序。只比HashMap慢一点;而在迭代访问时反而更快,因为它使用链表维护内部次序(HashMap是基于散列表实现的),源码来自android 源码.
LinkedHashMap定义两个属性
/**
* A dummy entry in the circular linked list of entries in the map.
* The first real entry is header.nxt, and the last is header.prv.
* If the map is empty, header.nxt == header && header.prv == header.
*/
transient LinkedEntry<K, V> header;//双向链表 /**
* True if access ordered, false if insertion ordered.
*/
private final boolean accessOrder;//默认情况false,插入顺序,true 访问顺序
在linkedhashmap构造器对链表进行初始化。
(1)get
从table数组中取(和hashmap一致),多了一步mainTail动作,把获取的数据,移到双向链表的尾部tail.
@Override public V get(Object key) {
/*
* This method is overridden to eliminate the need for a polymorphic
* invocation in superclass at the expense of code duplication.
*/
if (key == null) {
HashMapEntry<K, V> e = entryForNullKey;
if (e == null)
return null;
if (accessOrder)
makeTail((LinkedEntry<K, V>) e);//把访问的节点迁移到链表的尾部
return e.value;
}
int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];//从数组中获取
e != null; e = e.next) {
K eKey = e.key;
if (eKey == key || (e.hash == hash && key.equals(eKey))) {
if (accessOrder)
makeTail((LinkedEntry<K, V>) e);//把访问的节点迁移到链表尾部。
return e.value;
}
}
return null;
}
/**
* Relinks the given entry to the tail of the list. Under access ordering,
* this method is invoked whenever the value of a pre-existing entry is
* read by Map.get or modified by Map.put.
*/
private void makeTail(LinkedEntry<K, V> e) {
// Unlink e 在链表中删除该节点e
e.prv.nxt = e.nxt;
e.nxt.prv = e.prv;
// Relink e as tail 在尾部添加
LinkedEntry<K, V> header = this.header;
LinkedEntry<K, V> oldTail = header.prv;
e.nxt = header;
e.prv = oldTail;
oldTail.nxt = header.prv = e;
modCount++;
}
(2)put
添加到数据中,重载了preModify和addNewEntry,把存在的节点迁移到链表尾部或者新的节点添加到链表尾部。
//hashmap
public V put(K key, V value) {
if (key == null) {
return putValueForNullKey(value);
} int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
int index = hash & (tab.length - 1);
for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) {
if (e.hash == hash && key.equals(e.key)) {
preModify(e);//linkedhashmap 重载该方法,map存在该key,该节点迁移到链表尾部。
V oldValue = e.value;
e.value = value;
return oldValue;
}
} // No entry for (non-null) key is present; create one
modCount++;
if (size++ > threshold) {
tab = doubleCapacity();
index = hash & (tab.length - 1);
}
addNewEntry(key, value, hash, index);//linkedhashmap重载了这个方法
return null;
} //LinkedHashmap
@Override void addNewEntry(K key, V value, int hash, int index) {
LinkedEntry<K, V> header = this.header; // Remove eldest entry if instructed to do so.
LinkedEntry<K, V> eldest = header.nxt;
if (eldest != header && removeEldestEntry(eldest)) {
remove(eldest.key);
} // Create new entry, link it on to list, and put it into table 节点添加聊表尾部和table数组中
LinkedEntry<K, V> oldTail = header.prv;
LinkedEntry<K, V> newTail = new LinkedEntry<K,V>(
key, value, hash, table[index], header, oldTail);
table[index] = oldTail.nxt = header.prv = newTail;
}
(3)contains
containsValue 从链表中查询。hashmap从table数组中查询,进行该操作时,没有hashmap快(数组比链表迭代快)。
@Override public boolean containsValue(Object value) {
if (value == null) {
for (LinkedEntry<K, V> header = this.header, e = header.nxt;
e != header; e = e.nxt) {
if (e.value == null) {
return true;
}
}
return false;
}
// value is non-null
for (LinkedEntry<K, V> header = this.header, e = header.nxt; e != header; e = e.nxt) {//迭代链表
if (value.equals(e.value)) {
return true;
}
}
return false;
}
containKey 从数组中查询,和hashmap一致。
(4)
remove ,重载了postRemove
//在链表中删除节点
@Override void postRemove(HashMapEntry<K, V> e) {
LinkedEntry<K, V> le = (LinkedEntry<K, V>) e;
le.prv.nxt = le.nxt;
le.nxt.prv = le.prv;
le.nxt = le.prv = null; // Help the GC (for performance)
}
(5)迭代器
hashmap:是迭代数组 ,linkedhashmap 迭代链表。
(6)LruCache利用LinkedHashmap自身实现的lru功能,并对map进行容量限制。在进行put操作时,进行trimToSize.
public void trimToSize(int maxSize) {
while (true) {
K key;
V value;
synchronized (this) {
if (size < 0 || (map.isEmpty() && size != 0)) {
throw new IllegalStateException(getClass().getName()
+ ".sizeOf() is reporting inconsistent results!");
}
if (size <= maxSize || map.isEmpty()) {
break;
}
//迭代删除多余的节点,从链表头部开始删除。
Map.Entry<K, V> toEvict = map.entrySet().iterator().next();
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= safeSizeOf(key, value);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
java Linkedhashmap源码分析的更多相关文章
- java集合源码分析(六):HashMap
概述 HashMap 是 Map 接口下一个线程不安全的,基于哈希表的实现类.由于他解决哈希冲突的方式是分离链表法,也就是拉链法,因此他的数据结构是数组+链表,在 JDK8 以后,当哈希冲突严重时,H ...
- Java Reference 源码分析
@(Java)[Reference] Java Reference 源码分析 Reference对象封装了其它对象的引用,可以和普通的对象一样操作,在一定的限制条件下,支持和垃圾收集器的交互.即可以使 ...
- Java 集合源码分析(一)HashMap
目录 Java 集合源码分析(一)HashMap 1. 概要 2. JDK 7 的 HashMap 3. JDK 1.8 的 HashMap 4. Hashtable 5. JDK 1.7 的 Con ...
- java集合源码分析(三):ArrayList
概述 在前文:java集合源码分析(二):List与AbstractList 和 java集合源码分析(一):Collection 与 AbstractCollection 中,我们大致了解了从 Co ...
- Java集合系列[4]----LinkedHashMap源码分析
这篇文章我们开始分析LinkedHashMap的源码,LinkedHashMap继承了HashMap,也就是说LinkedHashMap是在HashMap的基础上扩展而来的,因此在看LinkedHas ...
- Java集合源码分析(五)HashSet<E>
HashSet简介 HashSet实现Set接口,由哈希表(实际上是一个HashMap实例)支持.它不保证set 的迭代顺序:特别是它不保证该顺序恒久不变.此类允许使用null元素. HashSet源 ...
- Java集合类源码分析
常用类及源码分析 集合类 原理分析 Collection List Vector 扩充容量的方法 ensureCapacityHelper很多方法都加入了synchronized同步语句,来保 ...
- java HashMap源码分析(JDK8)
这两天在复习JAVA的知识点,想更深层次的了解一下JAVA,所以就看了看JAVA的源码,把自己的分析写在这里,也当做是笔记吧,方便记忆.写的不对的地方也请大家多多指教. JDK1.6中HashMap采 ...
- 基于JDK1.8,Java容器源码分析
容器源码分析 如果没有特别说明,以下源码分析基于 JDK 1.8. 在 IDEA 中 double shift 调出 Search EveryWhere,查找源码文件,找到之后就可以阅读源码. Lis ...
随机推荐
- UOJ#454. 【UER #8】打雪仗
UOJ#454. [UER #8]打雪仗 http://uoj.ac/problem/454 分析: 好玩的通信题~ 把序列分成三块,\(bob\)先发出这三块中询问点最多的一块给\(alice\). ...
- js1
document.write('<h1>Hello World</h1>'); //写入网页 alert('Hello World'); console.log('Hello ...
- Unity 5 官方打包管理工具 Asset Bundle Manager
http://blog.csdn.net/suifcd/article/details/51570003 Unity5在Asset bundle 打包管理上采用了全新的方式,不需要再对每个文件进行MD ...
- mysql之 percona-xtrabackup 2.4.7安装(热备工具)
准备:os是centos6.7,提前下载并上传 percona-xtrabackup 安装包,下载网址为: https://www.percona.com/downloads/XtraBackup/L ...
- Python collections系列之可命名元组
可命名元组(namedtuple) 根据nametuple可以创建一个包含tuple所有功能以及其他功能的类 1.创建一个坐标类 import collections # 创建类, defaultd ...
- es6字符串的扩展学习笔记
1. 传统上,JavaScript只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中.ES6又提供了三种新方法. includes():返回布尔值,表示是否找到了参数字符串. st ...
- Linux驱动多线程 - 互斥量
1.内核多线程相关内容 1.1 头文件#include <linux/kthread.h> 1.2 定义/初始化变量 struct mutex SPI_work; /*定义互斥体*/ mu ...
- 安装 MongoDB。
1.安装 MongoDB. 1.为软件包管理系统导入公钥. Ubuntu 软件包管理工具为了保证软件包的一致性和可靠性需要用 GPG 密钥检验软件包.使用下列命令导入 MongoDB 的 GPG 密钥 ...
- C# WinForm中如何让当前应用程序只允许启动一个实例
我们在WinForm开发中,很多情况下是需要只允许让用户运行一个实例,那么代码其实很简单.只需要修改Program.cs文件,代码如下 static class Program { /// <s ...
- StackMapTable format error
环境:Oracle Java 7 , Mac OSX 报错如上图所示,主要是 Caused by: java.lang.ClassFormatError: StackMapTable format e ...