HashMap1.8源码
四个点核心点
- 初始化
- PUT
- 扩容
- GET
初始化
Node结构
transient Node<K,V>[] table;
初始化时为空的Node数组
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;
}
Treenode结构
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K,V> parent; // red-black tree links
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; // needed to unlink next upon deletion
boolean red;
TreeNode(int hash, K key, V val, Node<K,V> next) {
super(hash, key, val, next);
}
/**
* Returns root of tree containing this node.
*/
final TreeNode<K,V> root() {
for (TreeNode<K,V> r = this, p;;) {
if ((p = r.parent) == null)
return r;
r = p;
}
}
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
四个构造方法
initialCapacity:初始容量,默认是tableSizeFor(initialCapacity),根据传参找一个大于该数的2次幂数,比如定义是10,则初始化是16
loadFactor:负载因子,this.loadFactor = DEFAULT_LOAD_FACTOR;默认是0.75,0.75x16 = 12 ,即大于12则扩容if (++size > threshold)
// 构造一:传入初始容量,负载因子
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);
}
// 构造二:传入初始容量
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
// 构造三:无参构造
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
// 构造四:传入Map子类
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
空参关键默认容量是16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
下面才是在resize()方法里创建node数组
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];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];
tableSizeFor(initialCapacity)
源码方法
返回给定目标容量的 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;
}
演算过程
cap = 10
n = 10 - 1 = 9
9 // 0000 1001
n >>> 1 // 0000 0100
n |= n // 0000 1101 ->13
同理n=13
n >>> 2 // 0000 0011
n |= n // 0000 1111 -> 15
Integer.highestOneBit(10)); // 8
tableSizeFor(10)); // 16
为什么要2次幂?
n = tab.length
tab[i = (n - 1) & hash]
16: 0001 0000
15: 0000 1111
khash:0000 1010
& 与运算,位上都为1则为1
index:0000 1111
综上,使最高位后面位数都为1,使在与hashcode计算时,更好的散列在容量范围之内
PUT方法
参数一:key
参数二:值
其底层是putVal(hash(key), key, value, false, true);
对应:key的hash值,key,值,onlyIfAbsent,evict
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;
if ((tab = table) == null || (n = tab.length) == 0)
// 从这里看出,在new时并不会创建tab,而是在put的时候判断是否为空,去resize()
n = (tab = resize()).length;
// tab[i = (n - 1) & hash] n为什么要2次幂可以看出
if ((p = tab[i = (n - 1) & hash]) == null)
// 没有节点则创建一个node节点
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
// 否则hash冲突,看key值是不是一样,是则把p暂存在e,p和e就是已经存在的节点
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 这里可以看出在节点里有node和treenode两个类型
else if (p instanceof TreeNode)
// 如果是一颗树则插入树上
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
// 判断是一个链表而不是树
for (int binCount = 0; ; ++binCount) {
// 当bincount为0是,此时链表上有一个节点
if ((e = p.next) == null) {
// 创建节点
p.next = newNode(hash, key, value, null);
// static final int TREEIFY_THRESHOLD = 8;
// 也就是当bincount为7时为true,即当前有8个节点已经在链表上
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
// 当我创建第9个node时转树
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// 如果是有hash冲突并且key一样,则把新值覆盖到老值上
if (e != null) { // existing mapping for key
V oldValue = e.value;
// 如果onlyIfAbsent为fasle则覆盖老值,默认是false,putIfAbsent方法传入是true
if (!onlyIfAbsent || oldValue == null)
// 把put的值覆盖老值
e.value = value;
// 该方法是linkhashmap操作,空方法
afterNodeAccess(e);
// put方法会返回老值
return oldValue;
}
}
++modCount;
// 当当前所有的节点大于threshold时,选择resize()扩容
// newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
// threshold = newThr; = 0.75x16 = 12
// 也就是第一次有12个节点时就会选择扩容,第二次根据
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
扩容
resize()
cap是容量
threshold是阈值
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// 第一次是0,第二次是oldTab.length
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 第一次是12
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
// 最大阈值是2的32次
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 否则容量x2,当前x2,所以永远是2的次幂
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// 右移一位,当前x2
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
// 初始化容量大于0
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 默认初始化的值newCap = 16,newThr = 0.75x16 =12
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)
// 转移方法:当前的hash与容量进行与运算得到索引位置,
// 也就是为什么要2次幂,因为这样得到的结果只有两个情况
// 新下标 = 老下标
// 新下标 = 老下标 + 老容量
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;
// 判断他的最高位是0还是1,决定了是低位还是高位
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;
}
转移新数组后,hash值散列问题
khash: 0000 1010
扩容前:
16: 0001 0000
15: 0000 1111
15 0000 1111 0000 1111
kh 0000 1010 0101 0101
&
i 0000 1010 0000 0101
扩容后:
32: 0010 0000
31: 0001 1111 0001 1111
kh 0000 1010 0101 0101
&
0000 1010 --- 新下标 = 老下标
0001 0101 --- 新下标 = 0000 0101(扩容前hash) + 0001 0000(16扩容前长度) = 老下标 + 老长度
关键看最高位是0还是1,决定了新下标的位置
treeifyBin()
链表转红黑树
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
// 关键入口 当前有9个节点,也就是节点大于8
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
//替换给定哈希的 bin at 索引中的所有链接节点,除非表太小,在这种情况下会调整大小。
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// static final int MIN_TREEIFY_CAPACITY = 64;
// 如果数组的长度小于64,还是会选择扩容,而不是转红黑树
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 {
// 把node节点转treenode
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);
}
}
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
split
红黑树转链表
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
/**
* Splits nodes in a tree bin into lower and upper tree bins,
* or untreeifies if now too small. Called only from resize;
* see above discussion about split bits and indices.
*
* @param map the map
* @param tab the table for recording bin heads
* @param index the index of the table being split
* @param bit the bit of hash to split on
*/
//将树箱中的节点拆分为下部和上部树箱,如果现在太小,则取消树化。仅从调整大小调用;请参阅上面关于拆分位和索引的讨论。参数: map – 地图选项卡 – 用于记录垃圾箱头索引的表 – 被拆分的表的索引 位 – 要拆分的哈希位
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
// 同样要判断高低位,拆分两个
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
// 如果存在低位的
if (loHead != null) {
// UNTREEIFY_THRESHOLD = 6
// 并且低位的节点<=6,才会把树转为链表
if (lc <= UNTREEIFY_THRESHOLD)
// 把头节点转入转为链表
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
// 如果低位节点>6,并且没有高位的节点,就直接把树转移过去
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
// 判断高位节点
if (hiHead != null) {
// <=6
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
// 高位的在老下标+oldCap
// oldCap = bit
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
总结
链表转红黑树:条件是大于8并且数组长度大于64,散列在新数组上不一定在同一个链表上,根据hash高低计算新坐标,拆分成两个链表
红黑树转链表:条件是某一高低位上的节点小于等于6时文章来源:https://www.toymoban.com/news/detail-617296.html
putIfAbsent()
当key则存在则不覆盖文章来源地址https://www.toymoban.com/news/detail-617296.html
public V putIfAbsent(K key, V value) {
return putVal(hash(key), key, value, true, true);
}
putTreeVal()
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
/**
* Replaces all linked nodes in bin at index for given hash unless
* table is too small, in which case resizes instead.
*/
//替换给定哈希的 bin at 索引中的所有链接节点,除非表太小,在这种情况下会调整大小。
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);
}
}
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;
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;
}
到了这里,关于【HashMap1.8源码】十分钟带你深入HashMap1.8源码逐行解析的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!