hashMap源码学习记录

hashMap作为java开发面试最常考的一个题目之一,有必要花时间去阅读源码,了解底层实现原理。

首先,让我们看看hashMap这个类有哪些属性

  // hashMap初始数组容量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    // 最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

   // 装载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

   // 当某一桶下(key)的链表长度大于等于8时,该桶下的数据将由list结构转成红黑树结构
    static final int TREEIFY_THRESHOLD = 8;
    
    // hashMap 中的数组结构
    transient Node<K,V>[] table;

   // 当某一桶下的红黑树节点数小于等于6时,将变回list
    static final int UNTREEIFY_THRESHOLD = 6;

    // hashmap 进行红黑树化的桶数量最小大小,就是说即使某一个桶中已达到8个,但并不一定会转成红黑树,还要判断桶数量是否达到64,若没达到,但还是有一些桶中元素达到8个及以上,说明碰撞较为严重,进行扩容
    static final int MIN_TREEIFY_CAPACITY = 64;

    // 存放具体元素的集合
    transient Set<map.entry<k,v>> entrySet;
    // hashMap结构被修改的次数
    transient int modCount;
    // 临界值 当实际大小超过临界值时,hashMap会进行扩容
    int threshold
View Code

其次,来看看hashMap的构造方法

 public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
     
if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor;      // tableSizeFor()这个方法并没有建立 table数组,只是返回了不小于initialCapacity 的最小2次幂数如initialCapacity=15,那么返回16 this.threshold = tableSizeFor(initialCapacity); } public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } // 通过此构造方法,table将不再为空,具体原因下面会说 public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); }

tableForSize() 方法没有将table初始化,只是返回了不小于initialCapacity 的最小2次幂数,看看他是怎么做到的

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

第一步:将传入的cap-1,这是因为当传入的cap本来就是2的某次幂可以那么就不变

第二步:右移1位,然后进行或操作,这个操作把cap最左边的1和左边第二个1保留了下来,如cap=10,二进制表示位1010,右移1位得0101,进行或运算得1111,左边两位都为1;

第三、第四、第五步操作与第二步的原理一样;

第五步就得到了cap首个最左边1后面全是1的一个数,如cap原本为1001  -> 1111;

最后返回 n + 1 就是2的某幂次方。 

通过使用传入map的构造方法能将table初始化,那么我们就去看看 putMapEntries()这个方法

 final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                // 后面为什么还 +1.0F,应该是补转整型时丢失的精度,如6.66666转整型会变成6, 丢失了后面的那些小数
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();// 就是它,在table==null时会初始化table数组
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                // putVal() 方法里会有是否resize的判断,在table==null,将会执行resize()方法
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

上面提到 resize() 方法会初始化 table 数组,去源码看看是怎么回事 

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold; 
        int newCap, newThr = 0;
        // 原table不为null
        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 设置为默认初始容量16
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 如果cap大小是构造函数传入的,那么oldCap == 0,oldThr > 0, 下面的if条件成立
        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;
        
        // 原本table不为null,进行resize操作
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null; // 原本地址赋值为null,让gc回收
                    if (e.next == null)  // 桶中只有一个元素,直接重新哈希然后通过与运算来求余,这也是为什么容量必须设置为2的幂数的原因
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)  // 如是个红黑树节点,将对此node下的树进行重排  
                        ((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;
                       // 将此node下的同一链元素一分为二
                        do {
                            next = e.next;
                            //与原容量进行与操作,等于0说明在该链下node的hash值映射的索引范围是在oldCap内的,那么保持索引不变
                            if ((e.hash & oldCap) == 0) { 
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else { //映射范围超过oldCap,因为 newCap 等于 2 * oldCap,那么新的映射索引可方便计算为 j+oldCap        
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
             
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead; //放入新table,索引和之前一样
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead; //放入新table,索引为原索引+oldCap
                        }
                    }
                }
            }
        }
        return newTab;
    }

下面说说 hashMap 中较常用的 put 方法

 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

// put()方法实际是使用该方法
// onlyIfAbsent if true, don't change existing value
// 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; // 之前说到的在put的时候初始table
        if ((p = tab[i = (n - 1) & hash]) == null) // 没有发生冲突,直接存入
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // hashMap中已存在key对象,更新值即可        
            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); // 回调函数,hashMap中为空实现,主要为hashMap的子类linkedHashMap服务
                return oldValue;
            }
        }
    // 增加hashMap结构改变次数
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict); // 回调函数
        return null;
    }

下面将轮到 get() 方法了,去源码一探究竟

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

hashMap 中每个元素都是以 Node 的形式的,让我们具体看看 Node 这个类

   static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

       // 因为重写了equal方法,为保持约束,hashCode也需重写,可以看到该类重写的hashCode()方法是通过计算key和value这两个对象哈希值后进行异或得到的
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

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

但是,在进行 put 操作时,并不是直接拿上面代码中计算得到的 hashCode,而是使用 hashMap 这个外部类的 hash() 方法

static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

可以看到计算 哈希值 是把 高16位低16位 进行了异或,这是为了增大 哈希值 的随机性,因为桶数组的长度为2^n,取模运算(hash & (len-1))只取低位,故直接使用 keyhashcode() 作为 hash 很容易发生碰撞。 

hashMap源码学习暂时到这里,关于红黑树,之前有看过关于它的具体原理,现在也基本忘了,下次再去学习一下然后用博客记录下来。

参考链接:

https://blog.csdn.net/qazwyc/article/details/76686915

https://www.cnblogs.com/xiaoxi/p/7233201.html

https://blog.csdn.net/kenzhang28/article/details/80212936

 

猜你喜欢

转载自www.cnblogs.com/X-huang/p/10708435.html