hashmap源码解读
文章目录
一、HashMap1.8源码解读
二、解读内容
1.初始值
代码如下(示例):
/**
* The default initial capacity - MUST be a power of two.
* 默认的初始化容量,必须是2的幂
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
* 最大容量,
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
* 负载因子,主要是计算能容纳的最大元素
* 计算公式 threshold = 初始化capacity * loadFactor
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
* 链表转换为红黑树的阀值
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
* 红黑树转换为链表的阀值,扩容时才能发生
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
* 进行树化的最小容量,防止在调整容量和形态时发生冲突
* 4 * TREEIFY_THRESHOLD
*/
static final int MIN_TREEIFY_CAPACITY = 64;
2.Put解读
代码如下(示例):
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;
//i = (n - 1) & hash,数组的位置,就是当前位置的元素为空,则往数组赋值
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//如果当前key=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);
//如果链表长度>=7,8是阈值,直接转换为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果链表匹配了key,直接覆盖
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;
}
2.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;
//如果老的容量>0,老的容量大于等于最大的容量,则直接赋值最大的容量
if (oldCap > 0) {
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
}
//旧的大于0,直接将旧的赋值给新的
else if (oldThr > 0) // initial capacity was placed in threshold
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"})
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) {
//先将旧的元素的数组引用置空,便于jvm-回收
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
//链表有值>1
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//java8很巧妙,不用重新计算新的index值,由于是2的n次方,扩容前是 1111,扩容后index是11111,
// 所以值hash*(n-1)的值相比于原数组要么是 01111,11111,取决于hash值,也就是最高位,
//最高位是0,则数组坐标不变,最高位是1,则数组位置是=10000+原坐标=原长度+原坐标
//此表达式,目的是为了该元素在新旧数组的小标是否相同
// (oldCap - 1) * e.hash = (2 * oldCap - 1) * e.hash=oldCap * e.hash = 0;
//相同就是低位处理元素
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;
}
2.HashMap构造函数解读
代码如下(示例):
public HashMap(int initialCapacity, float loadFactor) {
//初始化的值小于0,直接抛异常
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//初始化的值大于最大容量,初始化值等于定义的最大容量
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//加载因子小于等于0,抛异常
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
//重新计算数组大小,赋值的大小如果不是2的n次方,则转换为2的n次方
this.threshold = tableSizeFor(initialCapacity);
}