HashMap源码分析
1. 继承结构
![](https://img.haomeiwen.com/i7484530/0945baf81ffc61f8.png)
2. 结构图
![](https://img.haomeiwen.com/i7484530/42bdd5b91cec6d29.png)
3. 关键常量
/**
* 默认初始化容量,必须是2的n次方
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量2的30次方
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默认加载因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 桶树化阈值(定义了当桶中的键/值对数量过多时转换为红黑树的阈值)
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 桶解除树化阈值(定义了当桶中的键/值对数量减少时解除红黑树的阈值)
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 表最小树化阈值
*/
static final int MIN_TREEIFY_CAPACITY = 64;
TREEIFY_THRESHOLD和MIN_TREEIFY_CAPACITY区别
结论:
TREEIFY_THRESHOLD定义了当桶中的键/值对数量过多时转换为红黑树的阈值,
MIN_TREEIFY_CAPACITY则限制了只有当哈希表的大小足够大时才会考虑进行这种转换。
3. 关键方法
计算hash值
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
![](https://img.haomeiwen.com/i7484530/a5ec5151614d3142.png)
疑问
这里可以看出只有n为2的n次方n-1末尾几位才会全是1
(n - 1) & hash才能得出从0到n-1的值
(n - 1) & hash相当于hash%n
为什么不用取余?因为位运算更快
计算容量
// 返回给定目标容量的二次方大小。
static final int tableSizeFor(int cap) {
int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
插入
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) == 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;
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);
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;
}
}
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;
}
通过hash找到bin
bin为空:插入
bin是树:e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
bin是链表:判断是否要树化
然后根据onlyIfAbsent判断书否插入
getNode,removeNode逻辑类似
扩容
final Node<K,V>[] resize()
用一个新数组替代旧数组
网友评论