https://www.jianshu.com/p/aa017a3ddc40
https://blog.youkuaiyun.com/qazwyc/article/details/76686915
一,HashMap数据结构
java8中,HashMap是基于数组加链表加红黑树实现的。

二,HashMap源码详解
1,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;
// (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;
//与桶中第一个元素的hash值,key值相等
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 将第一个元素赋值给e,用e来记录
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);
//节点数量到达阈值,调用 treeifyBin判断是否需要转为红黑树。
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//判断链表中节点的key值与新插入元素的key值是否相等,相等则跳出循环。
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//表示在桶中找到key值、hash值与插入元素相等的结点
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;
}
插入元素流程总结
(1)两次哈希计算桶的index
(2)看是否有碰撞,如果没有,直接插入
(3)碰撞后,如果是以链表的形式存在,遍历插入,如果插入后导致链表过长,则转为红黑树。如果节点已经
存在,则新值替换旧值
(4)碰撞后,如果是以红黑树的形式 存在,则直接加入红黑树。
2,扩容机制resize()详解
扩容做了两件事情
1,新哈希数组的申请以及老哈希数组的释放
2,重新计算桶的位置以将其插入到新tab中去。
每次扩容都会扩大table容量原来的2倍,一个记录在新table中的位置要么就和原来一样,要么就需要迁移到(oldCap + index)的位置上。
下面这个例子是我看过的讲hashmap扩容比较容易理解的一个。
假设原来的table大小为4,那么扩容之后会变为8,那么对于一个元素A来说,如果他的hashCode值为3,那么他在原来的table
上的位置为(3 & 3) = 3,那么新位置呢?(3 & 7) = 3,这种情况下元素A的index和原来的index是一致的不用变。再来看一个
元素B,他的hashCode值为47,那么在原来table中的位置为(47 & 3) = 3,在新table中的位置为(47 & 7) = 7,也就
是(3 + 4),正好偏移了oldCap个单位。
那么如何快速确定一个记录迁移的位置呢?因为我们的计算方法为:(hashCode & (length - 1)),而扩容将导致(length - 1)会新增一个1,也就是说,hashCode将会多一位来做判断,如果这个需要新判断的位置上为0,那么index不变,否则变为需要迁移到(oldIndex + oldCap)这个位置上去,下面举个例子吧:
还是上面的两个元素A和B,哈希值分别为3和47,在table长度为4的情况下,因为(3) = (11),所以A和B会有两位参与运算来
获得index,A和B的二进制分别为:
3 : 11
47: 101111
在table的length为4的前提下:
3-> 11 & 11 = 3
47-> 000011 & 101111 = 3
在扩容后,length变为8:
3-> 011 & 111 = 3
47-> 10111 & 00111 = 7
对于3来说,新增的参与运算的位为0,所以index不变,而对于47来说,新增的参与运算的位为1,所以
index需要变为(index + oldCap)
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) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
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) {
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;
}
3, 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;
// table已经初始化,长度大于0,且根据hash寻找table中的项也不为空
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;
}
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
三,HashSet
HashSet是基于HashMap的,核心方法也都是调用HashMap,这里不再多家赘述了。
本文详细解析了Java8中HashMap的数据结构,包括基于数组、链表和红黑树的实现方式,深入分析了put方法的插入流程、扩容机制以及get方法的元素获取过程。同时,文章还介绍了HashSet的核心方法实现。
1316

被折叠的 条评论
为什么被折叠?



