HashMap的底层实现原理

时间:2022-03-09 22:54:29

HashMap的底层实现原理
1,属性
static final int MAX_CAPACITY = 1 << 30;//1073741824(十进制)01000000000000000000000000000000(二进制);
static final float DEFAULT_LOAD_FACTOR = 0.75f;
transient Node<K,V> table;
int threhold;//代表容量临界值
2,构造方法,constructor

public HashMap(){

this.loadFactor = DEFAULT_LOAD_FACTOR;
    //调用无参的构造方法,默认加载因子为0.75f 
}

//初始化不为空的map 集合
public HashMap(Map<? extends E> m){
    this,loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m,false);
}

final void putMapEntries(Map<? extends K,? extends V> m,boolean evict){
    int s = m.size();
    if(s>0){
        if(table == null){
            float ft = ((float)s/loadFactor)+1.0F;
            int t = (ft < (float) MAXIMUM_CAPACITY ? (int) ft : MAXIMUM_CAPACITY)
            if(t > threhold){//初始化threhold==0;
                threhold = tableSizeFor(t);
       }else if(s > threhold){//非初始化的时候,调用putAll
               resize();
           
            //开始往链表里面添加元素
               for(Map.Entry<? extends Key, ? extends V> e : m.entrySet()){
                   K key = e.getKey();
                   K value = e.getValue();
                   putVal(hash(key),key,value,false,evict);
                                          }
                            }   
                     }
           }
}

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;
    }

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//初始化的时候容量为0
        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) //初始化的不为空的map集合的时候,已经确定了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;//重新赋值threshold,链表里面的要添加的元素超过这个参数,意味着要扩容
        @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;
    }

//这个算法的目的是找到大于等于cap的最小2的幂的值,n >>> 1,高位补0,不带符号位,(将二进制中高位的1向低位移),n |= n >>> 1 等同 n = n | n >>> 1, |:位移中的或,有真则真(有1 则 1),所以
n | n >>> 1 的值是增大的,同理 n | n >>> 2 也是增大的,直到n | n >>> 16, 因为MAXIMUM_CAPACITY 的值1 << 30 ,01000000000000000000000000000000,所以,最多有效位移是31位,(1 + 2 + 4 +8 +16)
因此到16 位之后,便可以找最小的2的幂的值。

//为什么要cap -1,因为如果cap 正好是2的幂,如果不减1,得到的结果就是cap 的2倍,例如,cap = 8,如果不减1,得到的结果是16,但是想得到的结果就是8.所以需要先减去1,最后再加上1.
  如果cap 的结果为9,减去1 之后为8,最后得到的结果是15,在加上1,结果为16,满足大于等于9的最小幂。所以需要先减去1.

static final int tableSizeFor(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) ? MAXMUM_CAPACITY : n +1 ;
}

HashMap类中的内部类Node<K,V>

static class Node<K,V> extends Map.Entry<K,V>
Map <Interface> Entry<K,V> 是Map内部的一个Interface

属性:
final int hash;
final K key
V value;
Node<K,V> next;

Node<K,V>是一个单向的链表结构

有参构造方法 public HashMap(Map<? extends K, ? extends V> m)总结:
这个构造方法,可以实现将一个map 集合放入到构造方法的参数中,可以创建一个新的对象,对象中已经存在一个已知的map集合。

首先将loadFactor加载因子赋值为默认的0.75f,然后再调用putMapEnTries(m,false)函数,通过传入的m集合的大小,通过tableSizeFor(cap)函数可以暂时获得容量临界值shreshold,(再次放入一个更大的集合,可能需要扩容)然后会通过循环遍历,将传入集合的key,value 遍历出来,再通过 putVal(hash(key), key, value, false, evict)函数,将key 和value 放入。
在putVal(hash(key), key, value, false, evict)函数中,首先判断Node<K,V> table 是否为null,或者为空,一般第一次初始化table 都是null,所以会调用final Node<K,V>[] resize()进行创建容储或者扩容,
调用此函数,会判断shreshold的值,若是>0,则会将int oldThr = threshold; newCap = oldThr; 同时重新设定容量临界点,
 float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
            一般来说,不超过1<<30 的话,就是newCap*loadFactor;
下次当容量超过这个newThreshold 的时候,就会再次扩容。
最后,Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];//生成大小为newCap的数组,newCap 的大小就是之前的oldThreshold.
        table = newTab;

因此可以看出,HashMap的底层数据结构是单向链表数组Node<K,V>[]。