1. HashMap类图
2.数据结构
数组中的元素类型
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; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } }
3.为什么HashMap的底层数组长度总是2的n次方
当底层数组的length为2的n次方时, hash & (length - 1)就相当于对length取模,其效率要比直接取模高得多,这是HashMap在效率上的一个优化
1)使用hash()方法对Key的hashCode进行重新计算,以防止质量低下的hashCode()函数实现。由于HashMap的支撑数组长度总是2的倍数,通过右移可以使低位的数据尽量的不同,从而使Key的hash值的分布尽量均匀;
2)使用hash & (length - 1)方法进行取余运算,以使每个键值对的插入位置尽量分布均匀;
public static void main(String[] args) { // hash & (length - 1) int hash = 100; int length = 8; // 1100100 System.out.println(Integer.toBinaryString(hash)); // length-1: 0000111 System.out.println(Integer.toBinaryString(length-1)); // 000100 相对于100 % 8 = 4 System.out.println(Integer.toBinaryString(hash & (length - 1))); length = 16; // 1100100 System.out.println(Integer.toBinaryString(hash)); // length-1: 0001111 System.out.println(Integer.toBinaryString(length-1)); // 000100 相对于100 % 16 = 4 System.out.println(Integer.toBinaryString(hash & (length - 1))); length = 32; // 1100100 System.out.println(Integer.toBinaryString(hash)); //length-1: 0011111 System.out.println(Integer.toBinaryString(length-1)); // 000100 相对于100 % 16 = 4 System.out.println(Integer.toBinaryString(hash & (length - 1))); }hash值不变,数字容量分别为8、16、32
length-1分别为:
0000111
0001111
0011111
4.什么时候触发扩容、怎么扩容
1)先插入再扩容 2)元素个数大于阈值,进行扩容,譬如阈值的计算(默认table大小为16,加载因子为0.75) 16*0.75=12,超过12就扩容 3)扩大到原来的数组的2倍
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; // 1.先插入再扩容 // 2.元素个数大于阈值,进行扩容,譬如阈值的计算(默认table大小为16,加载因子为0.75) 16*0.75=12,超过12就扩容 // 3.扩大到原来的数组的2倍 if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
扩容计算位置,无需重新equal和hash
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;
}
// 没超过最大值,就扩容为原来的2倍
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);
}
// 计算新的resize上限,即新的threshold值
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) {
// 把旧的bucket都移动到新的buckets中
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);
// 扩容后,键值对在新table数组中的位置与旧数组中一样
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
// 扩容后,键值对在新table数组中的位置与旧数组中不一样
// 新的位置=原来的位置 + oldCap
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
- 为什么(e.hash & oldCap)== 0时就放入lo链表,否则就是hi链表;
- 为什么 j + oldCap就是键值对在新的table数组中的位置;
1)JDK1.8不需要像JDK1.7的实现那样重新hash,
2)JDK1.8只需要看看原来的hash值新增的那个bit是1还是0就好了,
是0的话索引没变,
是1的话索引变成“原索引+oldCap”
这个设计确实非常的巧妙,既省去了重新hash值的时间,而且同时,由于新增的1bit是0还是1可以认为是随机的,因此resize的过程,均匀的把之前的冲突的节点分散到新的bucket了,这一块就是JDK1.8新增的优化点。
5.HashMap为什么引入红黑树而不是AVL树
可以参考https://www.cs.usfca.edu/~galles/visualization/Algorithms.html 去观察树的动态转换
例如:8、7、6、5、4、3、2、1依次插入
二叉树:
二叉查找树,也称有序二叉树(ordered binary tree),或已排序二叉树(sorted binary tree),是指一棵空树或者具有下列性质的二叉树:
若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
若任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树;
没有键值相等的节点(no duplicate nodes)
因为一棵由N个结点随机构造的二叉查找树的高度为logN,所以顺理成章,二叉查找树的一般操作的执行时间为O(logN)。但二叉查找树若退化成了一棵具有N个结点的线性链后,则这些操作最坏情况运行时间为O(N),如上图
AVL平衡二叉树:
平衡树解决了二叉查找树退化为近似链表的缺点,能够把查找时间控制在 O(logN),不过却不是最佳的,因为平衡树要求每个节点的左子树和右子树的高度差至多等于1,这个要求实在是太严了,导致每次进行插入/删除节点的时候,几乎都会破坏平衡树的规则,进而我们都需要通过左旋和右旋来进行调整,使之再次成为一颗符合要求的平衡树。
红黑树:
插入、删除很频繁的场景中,平衡树需要频繁着进行调整,这会使平衡树的性能大打折扣,为了解决这个问题,于是有了红黑树。
红黑树是不符合AVL树的平衡条件的,即每个节点的左子树和右子树的高度最多差1的二叉查找树,但是提出了为节点增加颜色,红黑树是用非严格的平衡来换取增删节点时候旋转次数的降低,任何不平衡都会在三次旋转之内解决,相较于AVL树为了维持平衡的开销要小得多。
AVL树是严格平衡树,因此在增加或者删除节点的时候,根据不同情况,旋转的次数比红黑树要多,所以红黑树的插入效率相对于AVL树更高。单单在查找方面比较效率的话,由于AVL高度平衡,因此AVL树的查找效率比红黑树更高。
实际应用中,
若搜索的频率远远大于插入和删除,则选择AVL,
若搜索和插入删除操作的频率差不多,应该选择红黑树。
6. 为什么说HashMap线程不安全
HashMap的线程不安全体现在会造成死循环、数据丢失、数据覆盖这些问题。其中死循环和数据丢失是在JDK1.7中出现的问题,在JDK1.8中已经得到解决,然而1.8中仍会有数据覆盖的问题,即在并发执行HashMap的put操作时会发生数据覆盖的情况。
JDK1.7 头插法会将链表的顺序翻转,这也是在多线程环境下会形成死循环的关键点。扩容造成死循环和数据丢失的详细过程这里不再赘述
JDK1.8的源码中已经没有transfer函数,因为JDK1.8直接在resize函数中完成了数据迁移。此外JDK1.8在进行元素插入时使用的是尾插法。
参考 彻底理解HashMap及LinkedHashMap_Hopefully Sky的博客-CSDN博客_linkedhashmap