1 字段
1.1 字段解读
//默认容量等于16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认加载因子,可以自己调节
static final float DEFAULT_LOAD_FACTOR = 0.75f;
final float loadFactor;
//链表转红黑树阈值,当>=8时候,转化为红黑树
static final int TREEIFY_THRESHOLD = 8;
//树还原为链表的阈值,当在扩容(resize())时(HashMap的数据存储位置会重新计算),在重新计算存储位置后,当原有的红黑树内数量 <= 6时,则将 红黑树转换成链表
static final int UNTREEIFY_THRESHOLD = 6;
//转化为树的最小容量,当哈希表中的容量 > 该值时,才允许将链表 转换成红黑树
static final int MIN_TREEIFY_CAPACITY = 64;
//hashMap的数组,当第一次使用的时候初始化,长度永远是2的幂次方
transient Node<K,V>[] table;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException).
*/
//map结构被修改的次数,比如新增,删除,扩容等操作
transient int modCount;
//进行扩容的阈值,容量*负载因子即是该值,当大于该值时进行扩容
int threshold;
1.2 待扣细节
这几个字段会有几个面试问题:参见文章《JDK8中HashMap源码细节死扣》
- 为什么负载因子默认是0.75?
- 为什么链表长度>=8才会树化?
- 为什么容量必须是2的幂次方?
- modCount是用来干嘛的?
- Map容量为什么不能为MAX_VALUE
2 内部类
2.1 Node<K,V>
static class Node<K,V> implements Map.Entry<K,V> {
//key的哈希值
final int hash;
final K key;
V value;
//下一个节点
HashMap.Node<K,V> next;
Node(int hash, K key, V value, HashMap.Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
}
2.2 TreeNode<K,V>
final class TreeNode extends LinkedHashMap.Entry {
TreeNode parent; // red-black tree links
TreeNode left;
TreeNode right;
TreeNode prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node next) {}
// 返回当前节点的根节点
final TreeNode root() {
for (TreeNode r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
}
3 初始化
3.1 源码
有多个初始化方法,这里就选一个
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
//超过最大容量取最大容量
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
this.loadFactor = loadFactor;
//tableSizeFor(initialCapacity) 作用?
this.threshold = tableSizeFor(initialCapacity);
}
//保证函数返回值是大于等于给定参数initialCapacity最小的2的幂次方的数值//比如传进来是15,那么得到的是16//传进来是17,那么大于它的最小2次幂是32,所以得到32
static final int tableSizeFor(int cap) {
//给定的cap 减 1,为了避免参数cap本来就是2的幂次方,这样一来,经过后续操作,cap将会变成2 * cap
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n = MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
3.2 待扣细节
这里运算不做说明,参见文章《JDK8中HashMap源码细节死扣》
4 put(key,value)
4.1 源码
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//key的哈希算法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node[] tab; //map的数组
Node p;
int n, i;//n是数组的长度,i是当前要进入put的元素所在数组的index
if ((tab = table) == null || (n = tab.length) == 0)//如果数组为null或者长度为0,则进行初始化 ,相当于懒加载,第一次put的 时候进行初始化
//这里就是初始化的resize()扩容
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//tab[i]没有Node,也就是没有hash冲突,则new一个Node,并复制到数组
tab[i] = newNode(hash, key, value, null);
else {//tab[i]不是空,也就是hash冲突了
Node e; K k;
//如果key一样,则覆盖节点
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)//如果该节点是红黑树的节点
e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
else {//不是红黑树,是链表
for (int binCount = 0; ; ++binCount) {
//从头开始遍历链表
if ((e = p.next) == null) {
//遍历到最后一个Node,则新建一个Node,插入到尾部,上一个Node的next指针指向新的Node
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1)
//当链表长度>=8,进行转化为红黑树
//当hash表容量小于最小转红黑树容量(64),不转变红黑树,只扩容
treeifyBin(tab, hash);
break;
}
//遍历过程中,发下key一样,则跳出循环
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//如果key原来是存在的,则返回原来的旧值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
//赋值为新值
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//走到这里,代表原先map中不存在该key值
//修改次数+1,如果key是存在的,在上面已经return了,不算做修改次数+1
++modCount;
//当容器容量大于阈值,进行扩容
//在java8中,扩容的时机是插入值后,再扩容,再java7中,如果大于阈值,是先扩容再插入。
if (++size > threshold)
//扩容
resize();
afterNodeInsertion(evict);
//因为key不存在,所以原先是没有值的,返回null
return null;
}
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) //当hash表容量小于最小转红黑树容量(64),不转变红黑树,只扩容
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
4.2 流程图
上面大致逻辑如下图:
4.3 待扣细节
- key如何hash计算?
- 根据key的hashi值,数组小标如何确定的?tab[(n - 1) & hash]
参见文章《JDK8中HashMap源码细节死扣》
5 resize()
5.1 源码
/**
* 扩容有2种使用情况:1.初始化哈希表(第一次put操作) 2.当前数组容量达到扩容阈值
*/
final Node[] resize() {
Node[] oldTab = table;//拷贝旧数组
int oldCap = (oldTab == null) ? 0 : oldTab.length;//旧map容量
int oldThr = threshold;
int newCap, newThr = 0;
// 针对情况2
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
//扩容前的数组容量超过最大值,则不再扩容
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 针对情况2:若无超过最大值,就扩充为原来的2倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
//newCap设置为oldCap的2倍并小于MAXIMUM_CAPACITY,且大于默认值, 新的threshold增加为原来的2倍
newThr = oldThr << 1; // double threshold
}
// 针对情况1:初始化哈希表
else if (oldThr > 0) // initial capacity was placed in threshold
// threshold>0, 将threshold设置为newCap,所以要用tableSizeFor方法保证threshold是2的幂次方
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 默认初始化
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 新生成一个table数组
Node[] newTab = (Node[])new Node[newCap];
table = newTab;
if (oldTab != null) {
// oldTab 复制到 newTab,遍历数组
for (int j = 0; j < oldCap; ++j) {
Node e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
// 如果只有一个节点,则直接赋值
//为什么要重新Hash呢?因为长度扩大以后,Hash的规则也随之改变。
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
// e为红黑树的情况
((TreeNode)e).split(this, newTab, j, oldCap);
else { // preserve order
//之所以定义两个头两个尾对象,是由于链表中的元素的下标在扩容后,要么是原下标+oldCap,要么不变
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node next;
do {
next = e.next;
//e.hash & oldCap,计算下标是否需要移动
// 下标没有改变
if ((e.hash & oldCap) == 0) {
if (loTail == null)
//第一个节点
loHead = e;
else
//加入到尾部
loTail.next = e;
loTail = e;
}
// 原下标 + oldCap
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
// 原下标对应的链表
if (loTail != null) {
//尾部节点next设置为null
loTail.next = null;
newTab[j] = loHead;
}
// 原索引+oldCap对应的链表
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
5.2 待扣细节
- 容量为啥有最大限制?
- 扩容时候,下标是否需要移动怎么判定的?
参见文章《JDK8中HashMap源码细节死扣》
6 get(key)
6.1 源码
public V get(Object key) {
Node e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node getNode(int hash, Object key) {
Node[] tab; Node first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node 总是检查第一个Node
((k = first.key) == key || (key != null && key.equals(k))))
//命中key直接返回
return first;
//走第一个Node没有命中key的逻辑
if ((e = first.next) != null) {
//如果大于一个Node
if (first instanceof TreeNode)
//如果是红黑树,则从树中去查找
return ((TreeNode)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;
}
7 总结
在Java8中,HashMap是一个数组+链表+红黑树的数据结构,如图所示。
在第一次put操作时候进行首次扩容,数组长度即为最大容量,当put一个元素时候,会根据key进行hash计算定位到数组下标,如果有hash冲突的话则进行链表插入(尾插),当链表长度大于8的时候,会转变为红黑树(注意:当hashmap最大容量还没达到64时候,不会树化,而是扩容)。当元素容量达到阈值时候,则进行扩容,是在插入元素后,才进行扩容,而不是先扩容再插入。扩容是按照原容量的两倍进行扩容,会根据key的hash值判断是留在原下标位置,还是原下标+扩容前容量的下标位置。