HashMap源码解析(简单易懂)

 
/*
2 每一个key-value存储在Node<K,V>中,HashMap由Node<K,V>[]数 3 组组成。 4 */ 5 static class Node<K,V> implements Map.Entry<K,V> { 6 final int hash; 7 final K key; 8 V value; 9 Node<K,V> next; 10 11 //hash:每个节点插入时先计算hash 12 Node(int hash, K key, V value, Node<K,V> next) { 13 this.hash = hash; 14 this.key = key; 15 this.value = value; 16 this.next = next; 17 } 18 19 public final K getKey() { return key; } 20 public final V getValue() { return value; } 21 public final String toString() { return key + "=" + value; } 22 23 public final int hashCode() { 24 return Objects.hashCode(key) ^ Objects.hashCode(value); 25 } 26 27 public final V setValue(V newValue) { 28 V oldValue = value; 29 value = newValue; 30 return oldValue; 31 } 32 33 public final boolean equals(Object o) { 34 if (o == this) 35 return true; 36 if (o instanceof Map.Entry) { 37 Map.Entry<?,?> e = (Map.Entry<?,?>)o; 38 if (Objects.equals(key, e.getKey()) && 39 Objects.equals(value, e.getValue())) 40 return true; 41 } 42 return false; 43 } 44 }
HashMap常量与属性:
常量:
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认初始化容量是16
static final int MAXIMUM_CAPACITY = 1 << 30;//数组的最大容量 2的30次方
static final float DEFAULT_LOAD_FACTOR = 0.75f; //默认加载因子 ,阈值=capacity*DEFAULT_LOAD_FACTOR
static final int TREEIFY_THRESHOLD = 8; //默认链表长度大于8时,链表转化成红黑数
static final int UNTREEIFY_THRESHOLD = 6; //默认元素个数小于6时,红黑数退化成链表
static final int MIN_TREEIFY_CAPACITY = 64;//在转变成树之前还会有一次判断,只有键值对数量大于64才会发生转换,
//这是为了避免在哈希表建立初期,多个键值对恰好被放入同一个链表中导致不必要的转化

属性:

transient Node<K,V>[] table; 


transient Set<Map.Entry<K,V>> entrySet;


transient int size;


transient int modCount;//扩容次数


int threshold;//阈值,超过这个值就扩容


final float loadFactor; //加载因子

方法:

1 static final int hash(Object key) {
2         int h;
3         return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
4     }
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

/**
* 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) {//onlyIfAbsent==true:如果key值已存在,则不改变其value值
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;//null或者长度为零,需要初始化大小,或者扩容
if ((p = tab[i = (n - 1) & hash]) == null) //(n - 1) & hash:确定index,因为n是2的次幂,n-1各进制位都为1,
// &:按位与 任何数与n-1做 &运算结果小于n-1,所以保证任何hash的下标都在n-1中 tab[i]
= newNode(hash, key, value, null);//p==null表明:该下标的数组节点未被使用,直接赋值 else {//hash在 Node<K,V>[] 数组产生冲突,则在该节点的链表或红黑树查找 Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))//要插入的元素和冲突节点的第一个元素相等 e = p;//p:保存根据hash值找到的节点,e保存实时查找的最后一次找到的元素 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的后面 p.next = newNode(hash, key, value, null);
//元素个数大于8,链表转红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; }

//遍历到了key相等的元素,退出遍历
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e;//e=p.next;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;//添加元素,modCount++ if (++size > threshold)//判断是否需要扩容 resize(); afterNodeInsertion(evict); return null;//默认值 }
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)//容量2倍,阈值2倍,
                newThr = oldThr << 1; // double threshold
        }
//oldCap>=0&& oldThr>0
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; }
原文地址:https://www.cnblogs.com/dengrong/p/8510829.html