zoukankan      html  css  js  c++  java
  • Java源码——HashMap的源码分析及原理学习记录

    学习HashMap时,需要带着这几个问题去,会有很大的收获:

      一、什么是哈希表

      二、HashMap实现原理

      三、为何HashMap的数组长度一定是2的次幂?

      四、重写equals方法需同时重写hashCode方法

    一.什么是哈希表

      在了解哈希表之前,先了解下其他数据结构的操作执行性能,数据结构的物理存储结构只有两种方式:顺序存储结构和链式存储结构(栈,队列,数,图等)

    数组:采用一段连续的存储单元来存储数据,对于指定下标的查找,时间复杂度为O(1);根据确定的值来查找,需要遍历数组,逐一进行比较,时间复杂度为O(n)。对于有序数组,可以采用二分查找,插值查找,斐波那契查找等方式,复杂度为O(logn);对于一般的插入删除操作。需要数组的移动,平均复杂度未O(n)。

    线性表:对于链表的新增,删除操作(在找到指定操作位置后),仅需要处理结点间的引用即可,时间复杂度为O(1),而查找操作需要遍历链表逐一比较,复杂度为O(n)

    二叉树:对于一颗相对平衡的有序二叉树,进行插入,查找没删除等操作,平均复杂度为O(logn)。

    哈希表:在不考虑哈希冲突的情况下,仅仅一次定位就可以完成添加,删除,查找等操作,时间复杂度为O(1),因为哈希表的主干就是数组。

      比如:需要新增或者查找某个元素,我们通过把当前元素的关键字通过某个函数映射到数组中的某个位置,通过数组下表一次定位就可以完成操作。

    其中这个函数一般称为哈希函数,这个函数的设计好坏会直接影响到哈希表的优劣。下图为在哈希表中执行插入操作:

    查找操作同理,先通过哈希函数计算出实际存储地址,然后从数组中对应地址取出即可。

      哈希冲突

      如果两个不同的元素,通过哈希函数得出的实际存储地址相同,换句话说,当对某个元素进行哈希运算,得到一个存储地址,然后要进行插入的时候,发现一家被其他元素占用了,这就是产生了哈希冲突,也叫哈希碰撞。哈希冲突的解决方法有多种:开放地址法(发生冲突,继续寻找下一块未被占用的存储地址),再散列函数法,链地址法(jdk1.8之前HashMap采用该方法,也就是数组+链表的方式,jdk1.8当hash值的节点数不小于8时,采用数组+链表+红黑树)。

    图一表示jdk1.8之前的hashmap结构,左边部分代表哈希表,也称为哈希数组,数组的每个元素都是一个单链表的头结点,链表是用来解决冲突的,如果不同的key映射到了数组的同一位置上,就将其放入链表中。所以当hash值相等的元素较多时,通过key依次在链表查找的效率较低,时间复杂度为O(n)。

    图二表示jdk1.8的hashmap的在同意hash值的节点数不小于8时的存储结构,不再采用单链表形式存储,而是采用红黑树。

    二.HashMap的实现原理

      HashMap的主干是一个Entry数组。Entry是HashMap的基本组成单元,每一个Entry包含一个key-value键值对

    //HashMap的主干数组,可以看到就是一个Entry数组,初始值为空数组{},主干数组的长度一定是2的次幂,至于为什么这么做,后面会有详细分析。
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

    (1)Entry是HashMap 的一个静态内部类

    static class Entry<K,V> implements Map.Entry<K,V> {
            final K key;
            V value;
            Entry<K,V> next;//存储指向下一个Entry的引用,单链表结构
            int hash;//对key的hashcode值进行hash运算后得到的值,存储在Entry,避免重复计算
    
            /**
             * Creates new entry.
             */
            Entry(int h, K k, V v, Entry<K,V> n) {
                value = v;
                next = n;
                key = k;
                hash = h;
            }

    (2)在HashMap中重要的属性字段

    //table就是存储Node类的数组,就是对应上图中左边那一栏,
      /**
         * The table, initialized on first use, and resized as
         * necessary. When allocated, length is always a power of two.
         * (We also tolerate length zero in some operations to allow
         * bootstrapping mechanics that are currently not needed.)
      */
    transient Node<K,V>[] table;
        
    /**
         * The number of key-value mappings contained in this map.
    *  记录hashmap中存储键-值对的数量
      */
    transient int size;
     
    /**
      * hashmap结构被改变的次数,fail-fast机制,由于HashMap非线程安全,在对HashMap进行迭代时,如果期间其他线程的参与导致HashMap的结构发生变化了(比如put,remove等操作),需要抛出异常ConcurrentModificationException
      */
    transient int modCount;
     
        /**
         * The next size value at which to resize (capacity * load factor).
         * 扩容的门限值,当size大于这个值时,table数组进行扩容
         */
        int threshold;
     
        /**
         * The load factor for the hash table.
         *
         */
     float loadFactor;
    /**
         * The default initial capacity - MUST be a power of two.
    * 默认初始化数组大小为16
         */
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
     
        /**
         * The maximum capacity, used if a higher value is implicitly specified
         * by either of the constructors with arguments.
         * MUST be a power of two <= 1<<30.
         */
        static final int MAXIMUM_CAPACITY = 1 << 30;
     
        /**
         * The load factor used when none specified in constructor.
    * 默认装载因子,
         */
        static final float DEFAULT_LOAD_FACTOR = 0.75f;
     
        /**
         * The bin count threshold for using a tree rather than list for a
         * bin.  Bins are converted to trees when adding an element to a
         * bin with at least this many nodes. The value must be greater
         * than 2 and should be at least 8 to mesh with assumptions in
         * tree removal about conversion back to plain bins upon
         * shrinkage.
    * 这是链表的最大长度,当大于这个长度时,链表转化为红黑树
         */
        static final int TREEIFY_THRESHOLD = 8;
     
        /**
         * The bin count threshold for untreeifying a (split) bin during a
         * resize operation. Should be less than TREEIFY_THRESHOLD, and at
         * most 6 to mesh with shrinkage detection under removal.
         */
        static final int UNTREEIFY_THRESHOLD = 6;
     
        /**
         * The smallest table capacity for which bins may be treeified.
         * (Otherwise the table is resized if too many nodes in a bin.)
         * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
         * between resizing and treeification thresholds.
         */
        static final int MIN_TREEIFY_CAPACITY = 64;

    HashMap有4个构造器,其他构造器如果用户没有传入initialCapacity 和loadFactor这两个参数,会使用默认值

    initialCapacity默认为16,loadFactory默认为0.75

    //可以自己指定初始容量和装载因子
        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;
            //重新定义了扩容的门限
            this.threshold = tableSizeFor(initialCapacity);
    }
     
    /**
         * Returns a power of two size for the given target capacity.
         */
        static final int tableSizeFor(int cap) {
            int n = cap - 1;
            //先移位再或运算,最终保证返回值是2的整数幂
            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;
        }
     
        /**
         * Constructs an empty <tt>HashMap</tt> with the specified initial
         * capacity and the default load factor (0.75).
         *
         * @param  initialCapacity the initial capacity.
         * @throws IllegalArgumentException if the initial capacity is negative.
         */
    //当知道所要构建的数据容量的大小时,最好直接指定大小,提高效率
        public HashMap(int initialCapacity) {
            this(initialCapacity, DEFAULT_LOAD_FACTOR);
        }
     
        /**
         * Constructs an empty <tt>HashMap</tt> with the default initial capacity
         * (16) and the default load factor (0.75).
         */
        public HashMap() {
            this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
        }
     
        //将map直接放入hashmap中
        public HashMap(Map<? extends K, ? extends V> 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) { // pre-size
                    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();
                for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                    K key = e.getKey();
                    V value = e.getValue();
                    putVal(hash(key), key, value, false, evict);
                }
            }
    }
     
     
    /**
         * Basic hash bin node, used for most entries.  (See below for
         * TreeNode subclass, and in LinkedMyHashMap for its Entry subclass.)
         */
        在hashMap的结构图中,hash数组就是用Node型数组实现的,许多Node类通过next组成链表,key、value实际存储在Node内部类中。
        public 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; }
     
            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;
            }
        }

    (3)在HashMap中重要的方法,在常规构造器中,没有为数组table分配内存空间(有一个入参为指定Map的构造器例外),而是在执行put操作的时候才真正构建table数组

     
    /**
         * Associates the specified value with the specified key in thismap.
         * If the map previously contained a mapping for the key, the old
         * value is replaced.
         *
    */
    public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);
        }
    static final int hash(Object key) {
            int h;
            //key的值为null时,hash值返回0,对应的table数组中的位置是0
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
     
    /**
         * 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) {
            Node<K,V>[] tab; Node<K,V> p; int n, i;
        //先将table赋给tab,判断table是否为null或大小为0,若为真,就调用resize()初始化
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
        //通过i = (n - 1) & hash得到table中的index值,若为null,则直接添加一个newNode
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            else {
            //执行到这里,说明发生碰撞,即tab[i]不为空,需要组成单链表或红黑树
                Node<K,V> e; K k;
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
        //此时p指的是table[i]中存储的那个Node,如果待插入的节点中hash值和key值在p中已经存在,则将p赋给e
                    e = p;
        //如果table数组中node类的hash、key的值与将要插入的Node的hash、key不吻合,就需要在这个node节点链表或者树节点中查找。
                else if (p instanceof TreeNode)
                //当p属于红黑树结构时,则按照红黑树方式插入
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                else {
          //到这里说明碰撞的节点以单链表形式存储,for循环用来使单链表依次向后查找
                    for (int binCount = 0; ; ++binCount) {
            //将p的下一个节点赋给e,如果为null,创建一个新节点赋给p的下一个节点
                        if ((e = p.next) == null) {
                            p.next = newNode(hash, key, value, null);
            //如果冲突节点达到8个,调用treeifyBin(tab, hash),这个treeifyBin首先回去判断当前hash表的长度,如果不足64的话,实际上就只进行resize,扩容table,如果已经达到64,那么才会将冲突项存储结构改为红黑树。
     
                            if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                                treeifyBin(tab, hash);
                            break;
                        }
        //如果有相同的hash和key,则退出循环
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            break;
                        p = e;//将p调整为下一个节点
                    }
                }
        //若e不为null,表示已经存在与待插入节点hash、key相同的节点,hashmap后插入的key值对应的value会覆盖以前相同key值对应的value值,就是下面这块代码实现的
                if (e != null) { // existing mapping for key
                    V oldValue = e.value;
            //判断是否修改已插入节点的value
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            ++modCount;//插入新节点后,hashmap的结构调整次数+1,保证并发访问时,若HashMap内部结构发生变化,快速响应失败
            if (++size > threshold)
                resize();//HashMap中节点数+1,如果大于threshold,那么要进行一次扩容
            afterNodeInsertion(evict);
            return null;
        }

    (4)扩容函数resize()分析

     
    /**
         * Initializes or doubles table size.  If null, allocates in
         * accord with initial capacity target held in field threshold.
         * Otherwise, because we are using power-of-two expansion, the
         * elements from each bin must either stay at same index, or move
         * with a power of two offset in the new table.
         *
         * @return the table
         */
        final Node<K,V>[] resize() {
            Node<K,V>[] oldTab = table;//定义临时Node数组型变量,作为hash table
            //读取hash table的长度
            int oldCap = (oldTab == null) ? 0 : oldTab.length;
            int oldThr = threshold;//读取扩容门限
            int newCap, newThr = 0;//初始化新的table长度和门限值
            if (oldCap > 0) {
                //执行到这里,说明table已经初始化
                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
            //用构造器初始化了门限值,将门限值直接赋给新table容量
                newCap = oldThr;
            else {              
     // zero initial threshold signifies using defaults
    //老的table容量和门限值都为0,初始化新容量,新门限值,在调用hashmap()方式构造容器时,就采用这种方式初始化
                newCap = DEFAULT_INITIAL_CAPACITY;
                newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
            }
            if (newThr == 0) {
                //如果门限值为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"})
           //初始化新的table数组
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
            table = newTab;
            //当原来的table不为null时,需要将table[i]中的节点迁移
            if (oldTab != null) {
                for (int j = 0; j < oldCap; ++j) {
                    Node<K,V> e;
                    //取出链表中第一个节点保存,若不为null,继续下面操作
                    if ((e = oldTab[j]) != null) {
                        oldTab[j] = null;//主动释放
                        if (e.next == null)
        //链表中只有一个节点,没有后续节点,则直接重新计算在新table中的index,并将此节点存储到新table对应的index位置处
                            newTab[e.hash & (newCap - 1)] = e;
                        else if (e instanceof TreeNode)
                        //若e是红黑树节点,则按红黑树移动
                            ((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 {
    //下面这段暂时没有太明白,通过e.hash & oldCap将链表分为两队,参考知乎上的一段解释
    /**
    * 把链表上的键值对按hash值分成lo和hi两串,lo串的新索引位置与原先相同[原先位
    * j],hi串的新索引位置为[原先位置j+oldCap];
    * 链表的键值对加入lo还是hi串取决于 判断条件if ((e.hash & oldCap) == 0),因为* capacity是2的幂,所以oldCap为10...0的二进制形式,若判断条件为真,意味着
    * oldCap为1的那位对应的hash位为0,对新索引的计算没有影响(新索引
    * =hash&(newCap-*1),newCap=oldCap<<2);若判断条件为假,则 oldCap为1的那位* 对应的hash位为1,
    * 即新索引=hash&( newCap-1 )= hash&( (oldCap<<2) - 1),相当于多了10...0,
    * 即 oldCap
    * 例子:
    * 旧容量=16,二进制10000;新容量=32,二进制100000
    * 旧索引的计算:
    * hash = xxxx xxxx xxxy xxxx
    * 旧容量-1 1111
    * &运算 xxxx
    * 新索引的计算:
    * hash = xxxx xxxx xxxy xxxx
    * 新容量-1 1 1111
    * &运算 y xxxx
    * 新索引 = 旧索引 + y0000,若判断条件为真,则y=0(lo串索引不变),否则y=1(hi串
    * 索引=旧索引+旧容量10000)
       */
     
                                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;
        }
     

    三.为什么HashMap的数组长度一定是2的次幂

    根据上面的方法分析,当发生哈希冲突并且size大于阈值的时候,需要进行扩容。扩容时,需要新建一个长度为之前数组2倍的新的数组,然后将当前数组中的元素全部传输过去,所以扩容相对来说是一个耗资源的操作。

    在jdk1.8之前采用位运算计算Entry数组的长度,即h & (length-1);位运算的效率远高于取余%运算。

    hash方法可以计算一个对象的hashcode,在bucket数组中的位置计算是i = (n-1)&hash(可以在很多方法中找到这个公式),它可以实现一个均匀分布。

    我们比如容量是n=32,那么32-1=31,31的二进制是11111

    用我们取得的对象的hashcode和31去进行与操作

    我们假设hashcode从1,2,3开始,分别得出的结果是

    00001 1

    00010 2

    ....

    11111 31

    发现是呈一个均匀分布的

    如果n=50呢,49的二进制是110001,再作同等假设,得出的值是

    000000  : 0
    000001  : 1
    010000  : 16
    010001  : 17
    100000  : 32
    100001  : 33
    110000  : 48

    110001  : 49

    这就是本质原因,你不用2的幂,保证不了均匀的分布

    我们正常的思维是进行一个%运算,但是%运算效率太过低下,所以采用2进制运算,同时为了保证2进制的情况下进行一个均匀分布,所以把容量设置成2的幂,这就是最正确的回答。

    四.重写equals方法需要重写hashcode方法

      重写equals()方法就必须重写hashCode()方法主要是针对HashSet和Map集合类型。集合框架只能存入对象(对象的引用(基本类型数据:自动装箱))。尽管我们在进行get和put操作的时候,使用的key从逻辑上讲是等值的(通过equals比较是相等的),但由于没有重写hashCode方法,所以put操作时,key(hashcode1)-->hash-->indexFor-->最终索引位置 ,而通过key取出value的时候 key(hashcode2)-->hash-->indexFor-->最终索引位置,由于hashcode1不等于hashcode2,导致没有定位到一个数组位置而返回逻辑上错误的值null(也有可能碰巧定位到一个数组位置,但是也会判断其entry的hash值是否相等,上面get方法中有提到。)

      所以,在重写equals的方法的时候,必须注意重写hashCode方法,同时还要保证通过equals判断相等的两个对象,调用hashCode方法要返回同样的整数值。而如果equals判断不相等的两个对象,其hashCode可以相同(只不过会发生哈希冲突,应尽量避免)。

  • 相关阅读:
    Representation Data in OpenCascade BRep
    Render OpenCascade Geometry Surfaces in OpenSceneGraph
    Render OpenCascade Geometry Curves in OpenSceneGraph
    OpenCascade Shape Representation in OpenSceneGraph
    Geometry Surface of OpenCascade BRep
    Geometry Curve of OpenCascade BRep
    Tyvj2017清北冬令营入学测试
    Spfa算法模板
    洛谷1016 旅行家的预算
    洛谷1290 欧几里得的游戏
  • 原文地址:https://www.cnblogs.com/FanJava/p/9621784.html
Copyright © 2011-2022 走看看