目录
1 HashMap
1.1 常量
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
// 一个随机值,用于序列化
private static final long serialVersionUID = 362498820763181265L;
/**
* 无参初始化时HashMap的容量
* 有参构造传入容量后,会被转成2的n次幂的容量
**/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 初始化的最大容量,也是底层数组初始化最大长度
static final int MAXIMUM_CAPACITY = 1 << 30;
// 负载因子,扩容的条件
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表转红黑树的阈值,超过8个,并且容量大于64的时候就变树。8个是因为泊松分布
static final int TREEIFY_THRESHOLD = 8;
// 红黑树转链表的阈值,小于6个就变链表。两者不同防止反复横跳
static final int UNTREEIFY_THRESHOLD = 6;
// 容量小于64时扩容而不是变成树。
static final int MIN_TREEIFY_CAPACITY = 64;
1.2 变量
// 最底层的数组,数组类型为Node,长度为2的幂次
// transient类型不会被序列化
transient Node<K,V>[] table;
/**
* AbstractMap用到此属性
* 缓存keySet和valueSet
*/
transient Set<Map.Entry<K,V>> entrySet;
// 当前map存储键值对的个数
transient int size;
// HashMap修改次数,使用迭代器遍历时可以检测其是否被修改,被修改则fail-fast
transient int modCount;
//HashMap的size大于threshold时会执行resize操作。 threshold=capacity*loadFactor
int threshold;
// 外部配置的负载因子
final float loadFactor;
1.3 内部类
/**
* 底层table的类型
* 1)求hash值的方式是对key和value的hash值进行异或
* 2)求equal的方式是key和value的hash值都相等
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
/**
* key的hash值与value的hash值进行异或,提高散列度,降低hash冲突
* 异或能更好保留各部分的特征,&运算会使值靠近0,|运算使值靠近1
* @return int
*/
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
1.4 方法
1.4.1 求key的hash
hash值为int类型,4字节32位。求一次key的hash,hash值的高16位不变,低16位与高16位取异或
好处:高低位特征混合,减少hash碰撞。
原因:根据hash值求其在数组的位置都是在低位
/**
* 如果key是null,hash值返回0、
* 否则取key的 hash值异或hash值无符号右移16位
* 数组长度较短时,求(n-1)&hash时会只让低位参与运算,所以让高16位与低16位异或后,在低16位能保留高低位的信息,减少hash碰撞
* 异或能更好保留各部分的特征,&运算会使值靠近0,|运算使值靠近1
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
1.4.2 计算table的长度
通过传入的容量,计算出比它大的最小的2的幂的值
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
1.4.3 get方法的处理逻辑
1) 通过 (n-1)&&hash 来确定key在table中的位置
2)总是判断第一个Node是否为符合要求的
3)根据该结点的类型判断为红黑树还是链表来遍历获取
/**
* 问:为啥要判断hash值后再判断key呢,直接判断key不可以吗?
* 答:相当于一个短路逻辑,==比equals效率高,数组某个位置链表的每个hash值可能不同,只是求的下标相同
* 1. 通过(n-1)&hash算出key在数组中的下标
* 2. 比较hash和key值,是否与该下标的元素相等
* 3. 如果不相等,判断下一节点是否存在,和类型
* 4. 如果是TreeNode类型,就去红黑树查找
* 5. 否则就遍历链表,直到找到链表结尾
*/
final Node<K,V> getNode(int hash, Object key) {
// 临时table
Node<K,V>[] tab;
// first为key在数组的位置的Node对象
Node<K,V> first, e;
int n; K k;
// 通过(n-1)& hash 计算出当前key在数组中的下标
if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
// 如果这个元素的hash值等于key的hash值,并且元素的key等于当前key,就返回这个元素
if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 如果当前元素的下一个节点不为空
if ((e = first.next) != null) {
// 判断如果是TreeNode类型,就到getTreeNode方法获取节点
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
// 否则是链表形态,遍历当前链表,如果hash值和key值都相等,则返回该节点
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
1.4.4 put方法的处理逻辑
1)先看该map是否为空,空则把table初始化成默认长度16
2)根据hash值求其在数组中位置,通过(n-1)&hash
- n为2的k次方,n-1的右k位都为1
- (n-1)&hash取了hash值的右k位
3)如果该位置为null则新建结点并放到这个位置
4)否则
- 根据hash和key值判断第一个节点是否为对应的key,是则替换该Node的value值
- 否则判断是树还是链表,根据对应的遍历方式找到Node并替换
5)判断当前map的大小,如果达到负载值就扩容
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 数组为空或长度为0 ,则初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 如果数组对应位置无元素,则创建节点放到数组对应位置
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 先判断hash是否相等,再判断key是否相等
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 = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
// 如果链表长度达到了阈值,并且数组长度大于等于64,则化树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 假如map里存在过对应key,根据条件判断是否覆盖
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;
}
1.4.5 扩容机制resize()
前提:
- oldCap为2的幂次
- 新数组长度 newCap=oldCap<<1
- e在原数组的下标 j = e.hash & (oldCap-1)
如果
- (e.hash & oldCap) == 0 如
- e.hash = 110 0 1010
- oldCap = 0001 0000
- j = 0000 1010
则
- e.hash&(oldCap<<1 -1 )==j 如
- e.hash = 110 0 1010
- oldCap<<1 = 001 0 0000
- j = 0000 1010
否则
- e.hash&(oldCap<<1 -1 )==j+oldCap
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// 获取旧数组的长度和负载值
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
// 初始化新数组的长度和负载值
int newCap, newThr = 0;
/**
* 计算新数组的长度和负载值
*
*/
if (oldCap > 0) {
// 旧容量大于等于最大容量时不扩容,但负载值变为Int最大值
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 新的负载值乘2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
// 如果旧容量小于等于0且旧的负载值大于0 ,新的容量设置为旧的负载值?
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 如果旧容量和就负载值都小于等于0,那么新容量为默认16,新负载值为默认负载因子*默认容量=12
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"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else {
/**
* 如原数组长度为16,新数组长度为32.
* loHead、loTail都用于新数组前16个元素
* hiHead、hiTail都用于新数组后16个元素
*/
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
/**
* 链表中的元素最终只会进到新数组两个下标位置,位于新数组的前半部分和后半部分
* 通过位运算,得知元素的新的位置,并让其重新引用后继结点,得到两个新的链表
* 最后将两个链表直接挂到新数组上
*/
next = e.next;
/**
* 避免再次求下标运算,
* 如果(e.hash & oldCap) == 0,说明e.hash在新数组中的位置跟在旧数组中一样
* 否则e.hash求的位置为oldCap的长度+在原数组中的位置
*
*/
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
/**
* e为位置在数组上的元素,通过循环,讲head和tail指针放到链表的头和尾
*
*/
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;
}
1.4.6 tableSizeFor
/**
* 返回大于cap的最小的2的幂次
*/
static final int tableSizeFor(int cap) {
// cap = 9
int n = cap - 1; //n=8 0000 0000 0000 1000
n |= n >>> 1; //n=12 0000 0000 0000 0100
n |= n >>> 2; //n=15 0000 0000 0000 0011
n |= n >>> 4; //n=15 0000 0000 0000 1111
n |= n >>> 8; //n=15
n |= n >>> 16; //n=15
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; // return 16
}
1.4.7 treeifyBin 树化前初始准备
- 必须链表长度达到树化阈值 ,并且数组长度达到最小树化长度,才可以树化,否则会扩容
- 这里将链表所有节点变成树类型节点,并形成双向链表
- 准备树化
/**
* 如果数组长度未达到最小化树长度,则会扩容
* 先变树类型的双向链表
* 尝试变成红黑树
*/
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)
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);
}
}
1.5 其它问题
1. 负载因子为什么是0.75
简化下结论:
- 负载因子过大,会导致hash冲突概率升高,查询效率降低
- 负载因子过小,会导致空间利用率低
- 0.75是权衡空间以及时间的结果
2. 树和链表转化阈值设计原因?
链表长度超过8会转化为树。树节点数小于6会转化为链表
防止频繁转换,根据泊松分布判断这样转化效率最高。