Java基础之(四)HashMap(jdk10)
jdk1.7中,当冲突时,在冲突的地址上生成一个链表,将冲突的元素的key,通过equals进行比较,相同即覆盖,不同则添加到链表上,此时如果链表过长,效率就会大大降低,查找和添加操作的时间复杂度都为O(n);但是在jdk1.8中如果链表长度大于8,链表就会转化为 红黑树,时间复杂度也降为了O(logn),性能得到了很大的优化。
当红黑数节点小于等于6会重新转换为链表。
1.7中采用数组+链表,1.8采用的是数组+链表/红黑树,即在1.8中链表长度超过一定长度后就改成红黑树存储。
1.7扩容时需要重新计算哈希值和索引位置,1.8并不重新计算哈希值,巧妙地采用和扩容后容量进行&操作来计算新的索引位置。
1.7是采用表头插入法插入链表,1.8采用的是尾部插入法。
在1.7中采用表头插入法,在扩容时会改变链表中元素原本的顺序,以至于在并发场景下导致链表成环的问题;在1.8中采用尾部插入法,在扩容时会保持链表元素原本的顺序,就不会出现链表成环的问题了。
代码分析:
/** * 默认初始容量为16,0000 0001 右移4位 0001 0000为16,主干数组的初始容量为16,而且这个数组 *必须是2的倍数(后面说为什么是2的倍数) */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * 最大容量为2的30次方 */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * 默认加载因子为0.75 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * 阈值,如果主干数组上的链表的长度大于8,链表转化为红黑树 */ static final int TREEIFY_THRESHOLD = 8; /** * hash表扩容后,如果发现某一个红黑树的长度小于6,则会重新退化为链表 */ static final int UNTREEIFY_THRESHOLD = 6; /** * 当hashmap容量大于64时,链表才能转成红黑树 */ static final int MIN_TREEIFY_CAPACITY = 64;
/** * 临界值=主干数组容量*负载因子 DEFAULT_INITIAL_CAPACITY *DEFAULT_LOAD_FACTOR
*/
int threshold;
HashMap构造方法:
//initialCapacity为初始容量,loadFactor为负载因子
public HashMap(int initialCapacity, float loadFactor) {
//初始容量小于0,抛出非法数据异常
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//初始容量最大为MAXIMUM_CAPACITY
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//校验 loadFactor 合法性
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
//将初始容量转成2次幂
this.threshold = tableSizeFor(initialCapacity);
}
//tableSizeFor的作用就是,如果传入A,当A大于0,小于定义的最大容量时, // 如果A是2次幂则返回A,否则将A转化为一个比A大且差距最小的2次幂。 //例如传入7返回8,传入8返回8,传入9返回16 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; }
//默认构造方法,负载因子为0.75,初始容量为DEFAULT_INITIAL_CAPACITY=16,初始 容量在第一次put时才会初始化 public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }
put方法:
static final int hash(Object key) {
int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
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;
//如果主干上的table为空,长度为0,调用resize方法,调整table的长度( if ((tab = table) == null || (n = tab.length) == 0)
/* 这里调用resize,其实就是第一次put时,对数组进行初始化。*/
n = (tab = resize()).length;
//存入的key 不存在 ,存入新增的key if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k;
//key存在 if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k)))) e = p;
//判断p是否是 红黑树节点 else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else {//p与新节点既不完全相同,p也不是treenode的实例 for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null);
//如果链表长度大于等于8 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
//如果添加的元素产生了hash冲突,那么调用//put方法时,会将他在链表中他的上一个元素的值返回
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount;
//如果元素数量大于临界值,则进行扩容
if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
转化为红黑树:
final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; // 数组长度小于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 { //转化为红黑树 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); } }
resize的源码详解,扩容机制,单元素如何散列到新的数组中,链表中的元素如何散列到新的数组中,红黑树中的元素如何散列到新的数组中?
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) { //当容量超过最大值时,临界值设置为int最大值 threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&oldCap >= DEFAULT_INITIAL_CAPACITY) //扩容容量为2倍,临界值为2倍 newThr = oldThr << 1; } else if (oldThr > 0) newCap = oldThr; else { 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; //将新的临界值赋值赋值给threshold Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; //新的数组赋值给table //扩容后,重新计算元素新的位置 if (oldTab != null) { //原数组 for (int j = 0; j < oldCap; ++j) { //通过原容量遍历原数组 Node<K,V> e; if ((e = oldTab[j]) != null) { //判断node是否为空,将j位置上的节点 oldTab[j] = null; if (e.next == null) //判断node上是否有链表 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; //尾节点的next设置为空 newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; //尾节点的next设置为空 newTab[j + oldCap] = hiHead; } } } } } return newTab; }
//红黑树
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) {
//小于6 转化为 链表 if (lc <= UNTREEIFY_THRESHOLD) tab[index] = loHead.untreeify(map); else { tab[index] = loHead; if (hiHead != null) // (else is already treeified) loHead.treeify(tab); } } if (hiHead != null) { if (hc <= UNTREEIFY_THRESHOLD) tab[index + bit] = hiHead.untreeify(map); else { tab[index + bit] = hiHead; if (loHead != null) hiHead.treeify(tab); } } }