HashMap源码学习

HashMap源码学习

  1. 基本的元素

    public class HashMap<K,V> extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable {
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16  初始数组容量为16
        static final int MAXIMUM_CAPACITY = 1 << 30;  //最大容量
        static final float DEFAULT_LOAD_FACTOR = 0.75f; //加载因子,扩容的时候用,不是满了才扩容
        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; //一维数组,是HashMap最基本的存储方式
        transient Set<Map.Entry<K,V>> entrySet; //调用entrySet()方法时返回的实例
        transient int size;//大小
        public HashMap() {//无参构造方法
            this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
        }
        }
    
  2. node类(存储的键值对)

    static class Node<K,V> implements Map.Entry<K,V> {//键值对以node的形式存储
            final int hash; //保存该节点的hash值
            final K key; //键
            V value;//值
            Node<K,V> next;//链表指向的下一个节点
        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final int hashCode() {
                return Objects.hashCode(key) ^ Objects.hashCode(value);
            }
        public final boolean equals(Object o) {
                if (o == this)
                    return true;
                if (o instanceof Map.Entry) {
                    Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                    if (Objects.equals(key, e.getKey()) &&
                        Objects.equals(value, e.getValue()))
                        return true;
                }
                return false;
            }
    }
    
  3. 获取key的hash值

    static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//用key的hashcode值异或上其本身高16位置,为了让高16位也能参与运算,影响到低十六位
        }
    
  4. put方法

    public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);//获取key的hash
        }
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                       boolean evict) {//这里的hash是key的hash
            Node<K,V>[] tab; Node<K,V> p; int n, i;
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length; // table为空的话先初始化
            if ((p = tab[i = (n - 1) & hash]) == null)//哈希算法转换为数组下标,(n - 1) & hash确定index
                tab[i] = newNode(hash, key, value, null);//在数组中没有值,键值对封装为Node,直接插入
            else { //有节点,if语句中赋值为p
                Node<K,V> e; K k;
                if (p.hash == hash && //p是数组中应当放置的地方的那个节点
                    ((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))))//也可用equals判断是否相等
                            break;
                        p = e;//找到了相同的key,赋值给e,后面替换
                    }
                }
                if (e != null) { // existing mapping for key  找到相同的key,将其替换
                    V oldValue = e.value;
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            ++modCount;
            if (++size > threshold)//超过load factor * current capcity就扩容,这说明是计算所存的所有值,而不是只算在数组中的值
                resize();
            afterNodeInsertion(evict);
            return null;
        }
    
    
  5. resize()扩充数组

    //大致意思就是说,当超过限制的时候会resize,然而又因为我们使用的是2次幂的扩展(指长度扩为原来2倍),所以,元素的位置要么是在原位置,要么是在原位置再移动2次幂的位置。因此,我们在扩充HashMap的时候,不需要重新计算hash,只需要看看原来的hash值新增的那个bit是1还是0就好了,是0的话索引没变,是1的话索引变成“原索引+oldCap”。
    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) {//把原来的每个buckets移动到新的之中
                    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 { //原索引+oldCap
                                    if (hiTail == null)
                                        hiHead = e;
                                    else
                                        hiTail.next = e;
                                    hiTail = e;
                                }
                            } while ((e = next) != null);
                            if (loTail != null) { //原索引放到bucket之中
                                loTail.next = null;
                                newTab[j] = loHead;
                            }
                            if (hiTail != null) {//原索引加上原来容量放到bucket之中
                                hiTail.next = null;
                                newTab[j + oldCap] = hiHead;
                            }
                        }
                    }
                }
            }
            return newTab;
        }
    
  6. get(Key k)方法

    public V get(Object key) {
            Node<K,V> e;
            return (e = getNode(hash(key), key)) == null ? null : e.value;
        }
    final Node<K,V> getNode(int hash, Object key) {//传入key的hash值
            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) {
                if (first.hash == hash && // always check first node
                    ((k = first.key) == key || (key != null && key.equals(k))))//直接命中第一个,直接返回
                    return first;
                if ((e = first.next) != null) {//未直接命中
                    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;
        }
    
  7. 总结

    1. 什么时候会使用HashMap?他有什么特点?
      是基于Map接口的实现,存储键值对时,它可以接收null的键值,是非同步的,HashMap存储着Entry(hash, key, value, next)对象。

    2. 你知道HashMap的工作原理吗?
      通过hash的方法,通过put和get存储和获取对象。存储对象时,我们将K/V传给put方法时,它调用hashCode计算hash从而得到bucket位置,进一步存储,HashMap会根据当前bucket的占用情况自动调整容量(超过Load Facotr则resize为原来的2倍)。获取对象时,我们将K传给get,它调用hashCode计算hash从而得到bucket位置,并进一步调用equals()方法确定键值对。如果发生碰撞的时候,Hashmap通过链表将产生碰撞冲突的元素组织起来,在Java 8中,如果一个bucket中碰撞冲突的元素超过某个限制(默认是8),则使用红黑树来替换链表,从而提高速度。

    3. 你知道get和put的原理吗?equals()和hashCode()的都有什么作用?
      通过对key的hashCode()进行hashing,并计算下标( n-1 & hash),从而获得buckets的位置。如果产生碰撞,则利用key.equals()方法去链表或树中去查找对应的节点

    4. 你知道hash的实现吗?为什么要这样实现?
      在Java 1.8的实现中,是通过hashCode()的高16位异或低16位实现的:(h = k.hashCode()) ^ (h >>> 16),主要是从速度、功效、质量来考虑的,这么做可以在bucket的n比较小的时候,也能保证考虑到高低bit都参与到hash的计算中,同时不会有太大的开销。

    5. 如果HashMap的大小超过了负载因子(load factor)定义的容量,怎么办?
      如果超过了负载因子(默认0.75),则会重新resize一个原来长度两倍的HashMap,并且重新调用hash方法。

posted @ 2020-11-08 16:55  星银  阅读(55)  评论(0)    收藏  举报