getNode的原理比较简单,源码解析如下
//根据hash值及key值查找元素 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) { //第一个元素key值相同,直接返回第一个元素 if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; //桶中有多个元素 if ((e = first.next) != null) { //如果是TreeNode类型,在红黑树中查找 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; }
HashMap扩容
源码解读
//HashMap的扩容,每次都按2倍扩容 final Node<K,V>[] resize() { //table是一个hash桶数组,oldTab指向该桶 Node<K,V>[] oldTab = table; //原始数组容量 int oldCap = (oldTab == null) ? 0 : oldTab.length; //原始阈值 int oldThr = threshold; int newCap, newThr = 0; //如果桶数组不为空 if (oldCap > 0) { //如果超过最大容量2的30次方,已经无法扩容 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 //如果桶数组为空,阈值也为0,初始化容量和阈值,一般为首次初始化并且没有指定初始容量的情况下,初始化容量为16 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; //如果桶数组对象不为空,先缓存到e,原始对象置为空,方便垃圾回收 if ((e = oldTab[j]) != null) { oldTab[j] = null; //桶中只有一个元素,则计算扩容后索引位置,并放置到新数组中 if (e.next == null) newTab[e.hash & (newCap - 1)] = e; //如果对象是TreeNode,加入到红黑树 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; } //索引变为'原索引+oldCap'情况 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; } //索引变为'原索引+oldCap'情况 if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
扩容后元素位置要么保持不变(如Node0,Node1),要么移动到2次幂位置(如Node4,Node5),即以e.hash&(newCap-1)来确定元素的下标位置。
要么索引不变,要么变成 '原索引+oldCap'
HashMap扩容.png
下图更直观的展示桶中有多个元素时,扩容后索引的变化情况
HashMap扩容.png