在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本身线程不安全的特性并没有改变。

最新文章

  1. PHP JSON
  2. winform窗体之间通过 windows API SendMessage函数传值
  3. 每个配置xml的含义作用
  4. js去除日期字符串时分秒
  5. Delphi中实现MDI子窗体(转)
  6. 关于Bean
  7. jquery的clone方法bug的修复
  8. 自动监控主从MySQL同步的SHELL脚本
  9. zDialog无法获取未定义或 null 引用的属性“_dialogArray”
  10. 关于下拉刷新你是否真的非常理解还是只会搬砖?附 Android 实例子源代码文件下载地址380个合集
  11. OpenStreetMap(OSM) JMap Viewer(Java swing map)
  12. InnoDB的配置
  13. markdown中如何插入公式
  14. Java中 VO、 PO、DO、DTO、 BO、 QO、DAO、POJO的概念(转)
  15. 使用select正确处理EOF的str_cli函数
  16. llinux其他权限
  17. Java Date实现加一天,年月日类推往后+1,日期+1,月份+1,年份+1
  18. inline-blcok 之间的空白间隙
  19. TEXT 6 Travelling with baggage
  20. spring框架学习(八)spring管理事务方式之注解配置

热门文章

  1. 持续优化云原生体验,阿里云在Serverless容器与多云上的探索
  2. 帝国CMS编辑器粘贴Word图片
  3. luogu P1020 导弹拦截 x
  4. Delphi实现获取磁盘空间大小的方法
  5. 【进阶技术】一篇文章搞掂:Spring Cloud Stream
  6. xpath进阶
  7. quick BI 修改列名备注
  8. Vagrant 手册之 box - 版本
  9. ping, telnet, tcping 命令使用及对比
  10. Jenkins 官网文档翻译汇总