Java HashMap源码分析
1、HashMap底层实现
transient Node<K,V>[] table;
(数组+链表)。数组的长度总是2的n次方
2、基本属性
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认容量16,必须是2的N次方(原因见#3)
static final int MAXIMUM_CAPACITY = 1 << 30; // 最大容量,必须是2的N次方
static final float DEFAULT_LOAD_FACTOR = 0.75f; // 默认负载因子0.75
static final int TREEIFY_THRESHOLD = 8; // 链表节点转换红黑树节点的阈值
3、定位数组索引位置
1、重新计算hash
// 减少碰撞
static final int hash(Object key) {
int h;
// 将hashCode的高16位参与运算
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
2、计算索引位置
int n = tab.length;
// &运算:0011 & 0101 = 0001。每一位上有0得0,都是1得1。
int index = (n - 1) & hash;
为什么再次处理hashCode()
:
因为当数组长度比较小时只有低16位参与运算,碰撞几率大。将原hash值右移16位,再与原hash值^运算产生的新hash高1
基于算法:
// 2^n为数组长度
x % 2^n = x & (2^n - 1)
这种计算方式在数组长度是2的n次方时得出的结果是均匀分布的(减少碰撞)。位运算有更高的效率,&运算占2个机器周期(一次逻辑运算和一次写)。
4、get()方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
// 计算索引位置并赋值给局部变量first
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 检查first节点的hash与key
if (first.hash == hash && // 总是检查第一个节点
((k = first.key) == key || (key != null && key.equals(k))))
return first;
// 第一个节点不是目标节点
if ((e = first.next) != null) {
// 如果是红黑树的节点使用获取树节点的方法
if (first instanceof TreeNode)
// 获取树的根节点,调用它find()
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 遍历链表,检查每个节点的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;
}
5、put()方法
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;
// 如果数组为null或者长度为0,调用resize()初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 计算索引,如果数组中该位置的元素为null,新增一个节点
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; // 要put的值已经存在
// 如果是一个树节点,使用树的设置值方法
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);
// 判断是否是第8个节点
if (binCount >= TREEIFY_THRESHOLD - 1)
treeifyBin(tab, hash); // 转成红黑树
break;
}
// 判断要存入的值是否已经存在于链表中
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e; // 指向下一个节点
}
}
if (e != null) { // 已经存在对这个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;
}
6、resize()方法
/**
* 初始化或者将数组的容量翻倍
*/
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) {
if (oldCap >= MAXIMUM_CAPACITY) {
// 容量已经超过最大容量,阈值设置为最大的int
threshold = Integer.MAX_VALUE;
return oldTab; // 不扩容
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY) // 容量扩展为原来2倍
// 数组容量的2倍小于最大容量并且大于等于初始的容量(16),新阈值变为原来的2倍
newThr = oldThr << 1;
}
else if (oldThr > 0)
// 数组容量为0,阈值大于0,新数组容量就是原来的阈值
newCap = oldThr;
else {
// 数组容量0,阈值0,使用默认容量和默认负载因子*默认容量来初始化
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 { // 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) == 0) {
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;
}
暂时就写这么多吧。