在JDK1.8中对HashMap的底层实现做了修改。本篇对HashMap源码从核心成员变量到常用方法进行分析。

  HashMap数据结构如下:

 

  先看成员变量:

  1、底层存放数据的是Node<K,V>[]数组,数组初始化大小为16。

/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

  2、Node<K,V>[]数组最大容量

/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

  3、负载因子0.75。也就是如果默认初始化,HashMap在size = 16*0.75 = 12时,进行扩容。

/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;

  4、将链表转化为红黑数的阀值。

 /**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;

  5、红黑树节点转换为链表的阀值

/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;

  6、转红黑树时,table的最小长度

/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;

介绍一下HashMap用hash值定位数组index的过程:

//HahsMap中的静态方法
static final int hash(Object key) {
int h;
return (key == null) ? : (h = key.hashCode()) ^ (h >>> );
} //定位计算
int index = (table.length - 1) & hash
  • 先得到key的hashCode值
  • 再将hashCode值与hashCode无符号右移16位的值进行按位异或运算。得到hash值
  • 将(table.length - 1) 与 hash值进行与运算。定位数组index

给一个长度为16的数组,以"TestHash"为key,进行定位的过程实例:

HashMap中Node就是放入的数据节点,代码定义为:

  static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;

  Node节点保存key的hash值和K--V,借助next可实现链表。

红黑树封装为TreeNode节点:

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}

介绍get()方法:

final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > &&
(first = tab[(n - ) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
  • index定位,得到该索引上的Node节点,赋值给first
  • 对first节点进行判断,如果是要找的元素,直接返回
  • first节点的next不为空,继续找
  • 如果first节点是红黑树,调用getTreeNode()获取值。
  • 不是红黑树,只能是链表。从头遍历,找到就返回。

  上面对于红黑树取值的getTreeNode()方法,看一下红黑树的遍历做法:

final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
TreeNode<K,V> p = this;
do {
int ph, dir; K pk;
TreeNode<K,V> pl = p.left, pr = p.right, q;
if ((ph = p.hash) > h)
p = pl;
else if (ph < h)
p = pr;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if (pl == null)
p = pr;
else if (pr == null)
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != )
p = (dir < ) ? pl : pr;
else if ((q = pr.find(h, k, kc)) != null)
return q;
else
p = pl;
} while (p != null);
return null;
}
  • 从do-while循环里的第一个if开始。如果当前节点的hash比传入的hash大,往p节点的左边遍历
  • 如果当前节点的hash比传入的hash小,往p节点的右边遍历
  • 如果key值相同,就找到节点了。返回
  • 左节点为空,转到右边遍历
  • 右节点为空,转到左边
  • 如果传入key实现了Comparable接口。就将传入key与p节点key进行比较,根据比较结果选择向左或向右遍历
  • 没有实现接口,直接向右遍历,找到就返回
  • 没找到,向左遍历

介绍put()方法:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == )
n = (tab = resize()).length;
if ((p = tab[i = (n - ) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = ; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - ) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
  • table为null,初始化
  • 定位到数组index,若该位置为空,直接放
  • 如果该位置上不为空,且hash和key与传入的值相同,说明key重复,直接将该节点赋值给e,结束循环
  • 如果该index上的节点是红黑树,调用putTreeVal()方法
  • 不是红黑树,只能是链表,遍历整个链表
  • 找到最后一个节点,在这个节点后面以k--v新增一个节点。
  • 判断链表长度,binCount达到7,也就是长度达到8。转为红黑树。
  • 遍历过程中,如果找到了相同key,就跳出循环。
  • 如果e不为空,说明遍历结束后存在key重复的节点。做值覆盖
  • 扩容判断

分析红黑树插入方法putTreeVal():

final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -;
else if (ph < h)
dir = ;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == ) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
} TreeNode<K,V> xp = p;
if ((p = (dir <= ) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= )
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
  • 查找root根节点
  • 从root节点开始遍历
  • 如果当前节点p的hash大于传入的hash值,记dir为-1,代表向左遍历。
  • 小于,记1,代表向右遍历
  • 如果key相同,直接返回
  • 如果key所属的类实现Comparable接口,或者key相等。先从p的左节点、右节点分别调用find(),找到就返回。
  • 没找到,比较p和传入的key值,结果记为dir
  • 根据dir选择向左或向右遍历
  • 依次遍历,直到为null,表示达到最后一个节点,插入新节点
  • 调整位置

分析HashMap扩容方法:

final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? : oldTab.length;
int oldThr = threshold;
int newCap, newThr = ;
if (oldCap > ) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << ) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << ; // double threshold
}
else if (oldThr > ) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == ) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = ; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - )] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == ) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
  • 通过一系列判断,确认新table的容量
  • 构造一个新容量的Node数组,赋值给table
  • 遍历旧table数组
  • 如果节点是单节点,直接定位到新数组对应的index位置下
  • 如果是红黑树,调用split方法
  • 遍历链表。
  • 如果e的hash值与老数组容量取与运算,值为0。索引位置不变
  • 如果e的hash值与老数组容量取与运算,值为1。这在新数组中索引的位置为老数组索引 + 老数组容量。
  • 链表放置

简要分析多线程下HashMap死循环问题:

  JDK1.7HashMap扩容时,对于链表位置变化,采用头插法进行操作。多线程下容易形成环形链表,造成死循环。

  JDK1.8时,会对于链表hash值与容量的计算结果。分成两部分,并改为插入到链表尾部。1.8以后不会再有死循环问题,只是有可能重复放置导致数据丢失。HashMap本身线程不安全的特性并没有改变。

源码分析--HashMap(JDK1.8)的更多相关文章

  1. HashMap 源码分析 基于jdk1.8分析

    HashMap 源码分析  基于jdk1.8分析 1:数据结构: transient Node<K,V>[] table;  //这里维护了一个 Node的数组结构: 下面看看Node的数 ...

  2. 【JDK】JDK源码分析-HashMap(2)

    前文「JDK源码分析-HashMap(1)」分析了 HashMap 的内部结构和主要方法的实现原理.但是,面试中通常还会问到很多其他的问题,本文简要分析下常见的一些问题. 这里再贴一下 HashMap ...

  3. HashMap实现原理及源码分析(JDK1.7)

    转载:https://www.cnblogs.com/chengxiao/p/6059914.html 哈希表(hash table)也叫散列表,是一种非常重要的数据结构,应用场景及其丰富,许多缓存技 ...

  4. JAVA源码分析-HashMap源码分析(二)

    本文继续分析HashMap的源码.本文的重点是resize()方法和HashMap中其他的一些方法,希望各位提出宝贵的意见. 话不多说,咱们上源码. final Node<K,V>[] r ...

  5. 【JDK】JDK源码分析-HashMap(1)

    概述 HashMap 是 Java 开发中最常用的容器类之一,也是面试的常客.它其实就是前文「数据结构与算法笔记(二)」中「散列表」的实现,处理散列冲突用的是“链表法”,并且在 JDK 1.8 做了优 ...

  6. LinkedList源码分析(jdk1.8)

    LinkedList概述 ​ LinkedList 是 Java 集合框架中一个重要的实现,我们先简述一下LinkedList的一些特点: LinkedList底层采用的双向链表结构: LinkedL ...

  7. CopyOnWriteArrayList 源码分析 基于jdk1.8

    CopyOnWriteArrayList  源码分析: 1:成员属性: final transient ReentrantLock lock = new ReentrantLock();  //内部是 ...

  8. HashMap源码分析-基于JDK1.8

    hashMap数据结构 类注释 HashMap的几个重要的字段 hash和tableSizeFor方法 HashMap的数据结构 由上图可知,HashMap的基本数据结构是数组和单向链表或红黑树. 以 ...

  9. jdk1.8源码分析-hashMap

    在Java语言中使用的最多的数据结构大概右两种,第一种是数组,比如Array,ArrayList,第二种链表,比如ArrayLinkedList,基于数组的数据结构特点是查找速度很快,时间复杂度为 O ...

随机推荐

  1. mysql 注入绕过小特性

    1. 注释 Select /*多行(单行)注释*/ version(); Select version(); #单行注释 Select version(); -- 单行注释 (两划线之后必须有空格) ...

  2. RPC的解释以及RPC和Restful、RPC和RMI的区别

    如何科学的解释RPC 说起RPC,就不能不提到分布式,这个促使RPC诞生的领域. 假设你有一个计算器接口,Calculator,以及它的实现类CalculatorImpl,那么在系统还是单体应用时,你 ...

  3. SpringBoot自定义Jackson配置

    为了在SpringBoot工程中集中解决long类型转成json时JS丢失精度问题和统一设置常见日期类型序列化格式,我们可以自定义Jackson配置类,具体如下: import com.fasterx ...

  4. 对webpack的初步研究1

    一.概念: 1.webpack的核心是用于现代JavaScript应用程序的静态模块捆绑器.当webpack处理您的应用程序时,它会在内部构建一个依赖关系图,它映射您的项目所需的每个模块并生成一个或多 ...

  5. 9:关于Maven工程的文件标识(定义java文件源码,资源文件)

  6. CKEditor粘贴图片上传功能

    很多时候我们用一些管理系统的时候,发布新闻.公告等文字类信息时,希望能很快的将word里面的内容直接粘贴到富文本编辑器里面,然后发布出来.减少排版复杂的工作量. 下面是借用百度doc 来快速实现这个w ...

  7. Android 中的 Matrix

    Matrix 是 Android SDK 提供的一个矩阵类,它代表一个 3 X 3 的矩阵 Matrix主要可以对图像做4种基本变换 Translate 平移变换 Rotate 旋转变换 Scale ...

  8. vue项目适应不同屏幕做的适配器

    一般宽度是1920的,但是有的电脑屏幕很窄,导致页面样式错乱,那么可以设置app.vue以及主页面里的样式宽度为1920px,超过了就auto. 如下: (app.vue) (home.vue) 原效 ...

  9. ResquestInfoServlet类通过访问HttpServletRequest对象的各种方法来读取HTTP请求中的特定信息,并且把它们写入到HTML中

    ResquestInfoServlet类通过访问HttpServletRequest对象的各种方法来读取HTTP请求中的特定信息,并且把它们写入到HTML中 ResquestInfoServlet.j ...

  10. wl

    <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Conten ...