脑中要构想出连贯的动画,一切都是以这个动画为基础的;然后给别人讲明白
HashMap源码
-
理解:
HashMap底层是数组+链表+红黑树组成,所以我们看源码的时候,要想到对应的数据结构。HashMap对应内部类:Node+TreeNode -
构造器:赋值加载因子
/**
* 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
}
- 面试题:为什么HashMap的长度是2的幂等数?
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
首先我们知道HashMap底层数组的长度默认是16,在计算hash(key)的过程中,我们希望得到key.hashCode()的下标位置需要落在0-15之间,我们完全可以 key.hashCode()%16来进行计算。但这样的效率不高呀,并且hash(key)也不够分散,由此引出了下面的操作。
效率: 取余的效率不高,计算机的位运算效率很高,因此我们将16改造成二进制从而进行位运算的操作。16取出开始和结尾的两个位置,在数组的代表的是0和15,转换位二进制看尾部,即:0对应0000、15对应1111。15=2^4-1=16-1 即(n-1)对应代码: tab[i = (n - 1) & hash]
分散:(h = key.hashCode()) ^ (h >>> 16)。先获得key的hashCode的值 h,然后 h 和 h右移16位 做异或运算。实质上是把一个数的低16位与他的高16位做异或运算,因为在前面 (n - 1) & hash 的计算中,hash变量只有末x位会参与到运算。使高16位也参与到hash的运算能减少冲突。(之前的效率问题只是低位参与了运算,而高位没有参与运算)
相关链接:HashMap:为什么容量总是为2的次幂
- put(K,V)方法:
- 底层数组的长度为0的时候,我们进行resize的操作:
DEFAULT_INITIAL_CAPACITY=1<<4;//初始化数组长度
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);//设定扩容的阈值(加载因子*数组长度) - 判断p=tab[i=(n-1)&hash]的位置是否有值,如果没有,newNode;有的话,进一步判断,如果桶的位置的hash和插入的hash相同,则进行替换;
- 判断p是否属于TreeNode类型;
- 以上不符合则进行链表的插入(JDK8是向链表的后面插入)、树化(TREEIFY_THRESHOLD=8和tab.length>64)、链化(UNTREEIFY_THRESHOLD=6);
- 如果容量已经大于等于MAXIMUM_CAPACITY = 1 << 30,那么此时不是扩容二倍,直接最大值;
- 扩容机制:newThr = oldThr << 1; 2倍;
- if(oldTab!=null) 此时将原HashMap里面的数据的转移新的HashMap里面;结论:元素要么转移到原来的位置上,或者是转移到原来位置*2的位置上;
相关链接:Java中HashMap底层实现原理(JDK1.8)源码分析
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
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;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
/**
* 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;
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;
}