HashMap 成员变量
主要是负载因子和阈值。
// 根据构造函数查看阈值的计算
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;
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Returns a power of two size for the given target capacity.
*/
// 大于cap的最小的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;
}
负载因子0.75的设定是因为在这个负载因子情况下,节点出现的频率在hash桶中符合泊松分布,在这个情况下每个碰撞位置的链表长度几乎不可能超过8。
再看查找操作
就两个步骤: 在getNode()方法里,第一先定位键值对所在桶的位置,然后再对链表或者红黑树进行查找。
// hash这个值是根据Node的key 通过hash(key)获取 n - 1 & hash 相当于 hash值对 n 取余
// 因为取余计算效率没有位运算高。
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) > 0 &&
(first = tab[(n - 1) & 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;
}
/* 之所以 高低位进行亦或的原因是因为直接获取hashCode值的话,在上面的那个 n - 1 & hash时 n比较小,
会导致hash 只有低位参与运算,因为n只有低位有数据, 高位都是0 , 高位& 1和0 产生的结果都是0,增加
了高低位亦或的操作后可以加大hash这个值的低位信息的随机性,变相让高位参与计算。 减少冲突几率。*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 初始化桶数组 table,table 被延迟到插入新数据时再进行初始化
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 等于链表中的第一个键值对节点时,则将 e 指向该键值对
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果桶中的引用类型为 TreeNode,则调用红黑树的插入方法
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);
// 如果链表长度大于或等于树化阈值,则进行树化操作
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 条件为 true,表示当前链表包含要插入的键值对,终止遍历
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 判断要插入的键值对是否存在 HashMap 中
if (e != null) { // existing mapping for key
V oldValue = e.value;
// onlyIfAbsent 表示是否仅在 oldValue 为 null 的情况下更新键值对的值
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 键值对数量超过阈值时,则进行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
扩容分析
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) {
//超过数组在java中最大容量就无能为力了,冲突就只能冲突
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//长度和最大容量都扩容为原来的二倍
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;
double threshold
}
//...... ......
//更新新的最大容量为扩容计算后的最大容量
threshold = newThr;
//更新扩容后的新数组长度
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;
//如果老数组对应索引上有元素则取出链表头元素放在e中
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//如果老数组j下标处只有一个元素则直接计算新数组中位置放置
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 {
preserve order
//能进来说明数组索引j位置上存在哈希冲突的链表结构
Node<K, V> loHead = null, loTail = null;
Node<K, V> hiHead = null, hiTail = null;
Node<K, V> next;
//循环处理数组索引j位置上哈希冲突的链表中每个元素
do {
next = e.next;
//判断key的hash值与老数组长度与操作后结果决定元素是放在原索引处还是新索引
if ((e.hash & oldCap) == 0) {
//放在原索引处的建立新链表
if (loTail == null) loHead = e;
else loTail.next = e;
loTail = e;
} else {
//放在新索引(原索引 + oldCap)处的建立新链表
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;
}
https://segmentfault.com/a/1190000012926722
https://www.cnblogs.com/fswhq/p/hashmap.html这篇文章讲述了1.7为什么死环
先把自己的理解讲一下。1.7在resize的transfer()方法当中采用了头插法(避免尾部遍历),对于桶中的链表通过头插插到新的数组对应索引的哈希桶中, 在多线程的情况下线程1会获得线程2扩展后的链表指向, 而这个链表指向已经被反转了。在线程1当中e = 3 next = 7;
而在线程二当中7.next又等于3. 所以这样就会形成一个死环。
在1.8当中的resize()的设计就不会有这种问题。核心就是用了双链表, 双链表避免了尾部遍历问题又避免了头插法带来的倒序导致的死环问题。哔哔这么多其实然并卵,多线程下就不该使用HashMap。
resize()源码默写导读: 首先需要准备6个变量 oldCap,oldTab,newTab,newCap,oldThr, newThr, 先对cap和thr变量根据情况进行赋值(不是重点), 然后对oldTab进行遍历, 然后分情况讨论,对于tab中的每个桶是否有哈希冲突,没有的话直接用取余操作找到这个元素在新的数组当中的索引赋值, 这一次遍历就结束了, 如果有哈希冲突就判断是树还是链表,(树的太复杂了就不看了, 就学下链表就可以了) 链表的话就需要创建两个双链表(2个头,2个尾)。用do while循环来不停的把这些元素放到新的数组上,放到lo还是hi 取决于e.hash & oldCap 是否等于0.