zoukankan      html  css  js  c++  java
  • HashMap 你真的了解吗?

                               

    一. hashmap简介

    HashMap是基于哈希表的Map接口的非同步实现。此实现提供所有可选的映射操作,并允许使用null值和null键。此类不保证映射的顺序,特别是它不保证该顺序恒久不变。

    HashMap 是一个散列表,它存储的内容是键值对(key-value)映射。
    HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。
    HashMap 的实现不是同步的,这意味着它不是线程安全的。它的key、value都可以为null。此外,HashMap中的映射不是有序的。

    HashMap 的实例有两个参数影响其性能:“初始容量” 和 “加载因子”。容量 是哈希表中桶的数量,初始容量 只是哈希表在创建时的容量。加载因子 是哈希表在其容量自动增加之前可以达到多满的一种尺度。当哈希表中的条目数超出了加载因子与当前容量的乘积时,则要对该哈希表进行 rehash 操作(即重建内部数据结构),从而哈希表将具有大约两倍的桶数。
    通常,默认加载因子是 0.75, 这是在时间和空间成本上寻求一种折衷。加载因子过高虽然减少了空间开销,但同时也增加了查询成本(在大多数 HashMap 类的操作中,包括 get 和 put 操作,都反映了这一点)。在设置初始容量时应该考虑到映射中所需的条目数及其加载因子,以便最大限度地减少 rehash 操作次数。如果初始容量大于最大条目数除以加载因子,则不会发生 rehash 操作。

    二. hashmap数据结构

    大概了解hashmap之后,知道了hashmap的键值对映射,知道了hashmap的线程不安全,知道了hashmap的put,get方法。觉得自己足够了解hashmap了吗?并不是,接着,让我们先去了解一下hashmap的底层数据结构。

    首先,ArrayList和LinkedList的数据结构我们非常了解

    ArrayList :

            ArrayList 底层数据结构是数组,查询效率比较高,增删效率比较低。

    可以参照一下Arraylist的源码,可以看出Arraylist的数据结构为数组

    public void add(int index, E element) {
            rangeCheckForAdd(index);
    
            ensureCapacityInternal(size + 1);  // Increments modCount!!
            System.arraycopy(elementData, index, elementData, index + 1,
                             size - index);
            elementData[index] = element;
            size++;
        }

    LinkedList:

     

    LinkedList 底层数据是链表(双向链表),查询效率比较低,增删效率比较高。

    源码验证:可以看出LinkedList为双向链表结构

     1 private static class Node<E> {
     2         //数据
     3         E item;
     4         //后面数据
     5         Node<E> next;
     6         //前面数据
     7         Node<E> prev;
     8 
     9         Node(Node<E> prev, E element, Node<E> next) {
    10             this.item = element;
    11             this.next = next;
    12             this.prev = prev;
    13         }
    14     }    

    由此看来,ArrayList查询速度快,增删慢,LinkedList查询速度慢,增删快,那么,如果我们想查询速度快并且增删慢的话,将两种数据结构相结合,就是我们要讲的HashMap

    HashMap : 数组  +  链表

    在这样的数据结构中,如果我们想存放数据的话,除了map中一定要有的Key和Value,还要有指向下个单元的next,根据刚才数据结构的分析,可以猜想到Hashmap的存储单元应该是这样的:

    Class Node{
       Key;
       Value; 
       Node next;  
    }

    让我们带着我们的猜想去看一下HashMap的源码,果然,我们的猜想是正确的,源码如下

    /**
         * Basic hash bin node, used for most entries.  (See below for
         * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
         *
       * 基本的hash存储单元
    /
    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; } }

     大家看到源码中的变量,正如我们所猜想的一样,有Key、Value还有Node<K,V> next,然后我们发现还有一个变量int hash我们不太清楚,这个等下再提。

    那么,在HashMap中,数组和链表究竟是怎样表示的?在源码中是如何体现的呢?我们接着去猜想验证。

    1. 数组的表示

    平时我们表示数组,如字符串数组,是String[],整型数组是Integer[],那在HashMap中,他的基本单元是node,那假如我们是HashMap的源码编写人员,那么我们可以写成

    Node[] table;

    table是我们随意取的变量值。接着,我们去源码中去看看在HashMap中数组是如何定义表示的:

     /**
         * 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;

    果然和我们猜想的一样,在HashMap中的数组是以Node<K,V>[]表示的。(transient关键字是不进行序列化的意思)

    2. 数组的大小是如何定义设置的呢

    初始化大小:

    /**
         * The default initial capacity - MUST be a power of two.必须是2的n次幂
         */
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    这里我们可以看到数组的初始化大小为 1 << 4 ,这里是个位运算,1 << 4 是 1000,转化为十进制是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;

    当数组的大小如果不够用了,就要进行扩容。但是并不是全部都用完了再去扩容,如果全部用完再去扩容的话,性能会下降,存取效率也会受到影响。在HashMap中,如果用了数组大小的0.75倍,也就是四分之三的容量之后,就需要扩容

    /**
         * The load factor used when none specified in constructor.
         */
        static final float DEFAULT_LOAD_FACTOR = 0.75f;

    如数组大小定义为16,当超过12的时候,就要求去进行扩容,那么在HashMap中肯定会有一个值去记录目前占用的空间内存:

     /**
         * The number of key-value mappings contained in this map.
         */
        transient int size;

    我们用size来记录目前占用的空间内存,大家看一下HashMap中最常用的put方法中有这么一串代码:

     if (++size > threshold)
                resize();
      // (The javadoc description is true upon serialization.
        // Additionally, if the table array has not been allocated, this
        // field holds the initial array capacity, or zero signifying
        // DEFAULT_INITIAL_CAPACITY.)
        int threshold;

    这串代码的含义是什么呢?

    每当我们往HashMap中put一个值后,size就会增加1,这个threshold我们通过英文注释可以了解到,这个变量就是我们之前说的那个要求扩容的临界值,是现有内存的0.75倍。当现在的内容超过这个临界值时,就需要进行扩容了。

     3.链表的长度是如何限制的呢?

    让我们去源码中看一下在Hashmap中链表的长度是如何限制的呢?

     /**
         * 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;

    在源码中我们可以看到HashMap链表的长度限制为8。但是,通过英文注释我们可以看到,当链表的长度并不是不能超过8,当长度大于8时,数据结构会变形,表现形式就变成了红黑树(JDK1.8之后)。

     三. 源码分析

    基本的数据结构和Hashmap的设计思想我们已经大概了解了,现在我们要去正式的走近HashMap的源码了

    HashMap最核心的代码肯定是我们经常用的put和get方法。

    put方法:

        /**
         * Associates the specified value with the specified key in this map.
         * If the map previously contained a mapping for the key, the old
         * value is replaced.
         *
         * @param key key with which the specified value is to be associated
         * @param value value to be associated with the specified key
         * @return the previous value associated with <tt>key</tt>, or
         *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
         *         (A <tt>null</tt> return can also indicate that the map
         *         previously associated <tt>null</tt> with <tt>key</tt>.)
         */
        public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);
        }

    在put方法中,key和value这两个参数我们已经了解了,那么,这个hash(key)是什么含义呢?

    首先,我们要先考虑一个问题,每当一个node结点进入HashMap中时,究竟该放入哪里呢?

    结论就是:这个key值通过这个hash函数过滤之后的数值就是存放位置的一个标识,让我们去看一下这个hash函数是如何实现的

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

    从这里我们可以看出,这个不仅仅是得到key的hashcode值那么简单,还做了一些操作,那么为什么要如此复杂的计算这个数值呢?

    这是因为hashcode容易重复,不同的元素存储时容易处在同一个数组的下标位置,还有一个问题,这个hashcode值较大,容易出现数组越界的问题。 

    这里将hashcode值与他本身向右位移了16位的值做了一个异或。总结一下就是:

    hash函数就是将高16位和低16位做一个异或运算,然后得到一个结果来确定node节点的存放位置

    作用:尽量让Node落点分布均匀,减少碰撞的一个概率,如果碰撞概率高了,就势必导致数组下标下的链表长度太长。

    在这里,我们举个具体的数值去观察一下,一个Key的hashcode如果是3254239,他的高16位不变,与他的低16位做一个异或得到的值为3812。

    那我们存放的位置就是table[3812]吗?,显然这个长度太大了,我们还是得去限制一下这个长度,保证这个数组下标的位置在我们定义的数组大小之内。

    那么假如我们的数组大小为16的话,我们可以将3812对16取余

    3812 % 16 < 16,我们发现,这样去做的话取到的数值一定会小于我们定义的数组大小。那么,在hashmap源码中是这样实现的吗?

    n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)

    奇怪的是,我们设想的方式是取模,为什么源码中取了(n-1)和hash值的与运算呢?让我们去看一下他们的值是否是等价的。

    按照源码中来说,这个数组下标就是 (16 - 1) & 3812 = 15 & 3812,

    那么我们就要去证明  15 & 3812  ===  3812 % 16 这个是否成立

    15用二进制表示是 001111, 那么不管3812的二进制数是什么,他们的与运算的值也永远不会超过15,就是>=15,我们发现这和我们的取模运算的结果是一样的,这是hashmap源码里一个比较精秒的地方。

    那为什么要用这种方式呢?

    因为与运算要比我们的取模运算速度快,效率高

    我们再回过头看一串代码

     /**
         * The default initial capacity - MUST be a power of two.
         */
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    在这里,为什么要一定强调 数组的大小必须是2的n次幂呢,让我们举个例子来看一下,如果数组的自定义初始化大小为15

    那么 15 -1 = 14 ,14用二进制表示就是001110,那么与hash值做了与运算之后,得到的这个数值可能就会大于这个数组大小的规定值,还有就是不论hash值的这位数字是0还是1,得到的这个位数总会是0,那么结点的落点位置就很可能会重叠在一起,所以,这个数组的大小必须是2的n次幂。

    那么,2的n次幂减1的二进制数的后几位一定是1吗?我们验证一下

    16  15  01111

    32  31  011111

    64   63  0111111,没有问题

    推出: 数组大小不够用了,我希望扩大数组的大小,也要 * 2。 

    做了这么多的铺垫,接下来让我们完整的去看一下HashMap中的put方法

     1     /**
     2      * Implements Map.put and related methods
     3      *
     4      * @param hash hash for key
     5      * @param key the key
     6      * @param value the value to put
     7      * @param onlyIfAbsent if true, don't change existing value
     8      * @param evict if false, the table is in creation mode.
     9      * @return previous value, or null if none
    10      */
    11     final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
    12                    boolean evict) {
    13         //定义几个局部变量供接下来使用
    14         Node<K,V>[] tab; Node<K,V> p; int n, i;
    15         //这里将全局变量table,也就是我们刚才说的数组形式,赋给了局部变量tab
    16         if ((tab = table) == null || (n = tab.length) == 0)
    17         //如果数组的大小为空,就用resize方法来对数组进行初始化
    18             n = (tab = resize()).length;
    19         //计算节点的落点位置
    20         if ((p = tab[i = (n - 1) & hash]) == null)
    21             //如果为空则可以放置
    22             tab[i] = newNode(hash, key, value, null);
    23         else {
    24             //如果数组该位置有节点,则往下压,为链表结构
    25             Node<K,V> e; K k;
    26             //如果key的值是一样的,则保留老值
    27             if (p.hash == hash &&
    28                 ((k = p.key) == key || (key != null && key.equals(k))))
    29                 e = p;
    30             else if (p instanceof TreeNode)
    31                 //如果发现下面的结构已经是一个二叉树的话,就用红黑树的方式去储存
    32                 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
    33             else {
    34                 //遍历链表
    35                 for (int binCount = 0; ; ++binCount) {
    36                     if ((e = p.next) == null) {
    37                         //如果下一个节点为空,则可以放置
    38                         p.next = newNode(hash, key, value, null);
    39                         //如果放置之后正好为8的话,要进行链表向红黑树转化的过程
    40                         if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
    41                             treeifyBin(tab, hash);
    42                         break;
    43                     }
    44                     if (e.hash == hash &&
    45                         ((k = e.key) == key || (key != null && key.equals(k))))
    46                         break;
    47                     p = e;
    48                 }
    49             }
    50             if (e != null) { // existing mapping for key
    51                 //key值重复的话,保留老的值
    52                 V oldValue = e.value;
    53                 if (!onlyIfAbsent || oldValue == null)
    54                     e.value = value;
    55                 afterNodeAccess(e);
    56                 return oldValue;
    57             }
    58         }
    59         ++modCount;
    60         //判断数组的大小是否超过了一个阈值,0.75倍的值
    61         if (++size > threshold)
    62         //超过大小后重新初始化   
    63             resize();
    64         afterNodeInsertion(evict);
    65         return null;
    66     }            

    我们发现这个resize()方法调用了两次,他的作用是:

    1.数组的初始化

    2.数组的扩容

    源码分析: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;
            //如果数组存在,oldCap代表数组的长度
            int oldCap = (oldTab == null) ? 0 : oldTab.length;
            int oldThr = threshold;
            int newCap, newThr = 0;
            if (oldCap > 0) {
            //如果数组的大小大于0
                if (oldCap >= MAXIMUM_CAPACITY) {
                    //如果数组的大小大于最大值,不需要扩容
                    threshold = Integer.MAX_VALUE;
                    return oldTab;
                }
                //进行扩容,位运算,相当于乘以2
                else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                         oldCap >= DEFAULT_INITIAL_CAPACITY)
                    //相应的临界值(阈值)也要乘2
                    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) {
                    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) {
                                    //省去了e.hash和oldcap-1 的与操作,如果为0,则hash的第5位是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;
        }

    接着,我们去看了看get方法的源码,发现和put方法大同小异,也是通过key去找到对应的节点,然后根据数组或者红黑树这些结构去判断,然后获取节点的key和value。

    分享阿里的一个hashmap的面试题:

    通过hashmap的初步了解,到hashmap数据结构的分析,到源码的透彻分析,相信你们对hashmap已经有了充分的了解。

     

  • 相关阅读:
    使用require.context引入模块
    npm link的使用
    mysql 链接远程数据库
    微信错误:errcode=45015, errmsg=response out of time limit or subscription is canceled
    微信公众号发送模板消息
    VS CODE 开发php实现断点调试
    uni 蓝牙 安卓 监听不到返回数据 不可写入
    vue3.0 兄弟组件传值
    二叉查找树的实现和删除
    模块二:ES新特性与TypeScript、JS性能优化
  • 原文地址:https://www.cnblogs.com/GodHeng/p/8869057.html
Copyright © 2011-2022 走看看