java.util包——HashMap类

java.util 
类 HashMap<K,V>

java.lang.Object
  java.util.AbstractMap<K,V>
      java.util.HashMap<K,V>

类型参数:

K - 此映射所维护的键的类型

V - 所映射值的类型

所有已实现的接口:

SerializableCloneableMap<K,V>

直接已知子类:

LinkedHashMapPrinterStateReasons

public class HashMap<K,V> extends AbstractMap<K,V>

                                              implements  Map<K,V>, Cloneable, Serializable

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

先看几道面试题看看自己掌握多少:

先来段代码:

import java.util.HashMap;

public class HashMapTest {
    public static void main(String args[]) {
        HashMap<Integer, String> hm = new HashMap<Integer, String>();
        hm.put(1, "jack");
        hm.put(2, "tom");
        hm.put(3, "vicky");
        hm.put(4, "cat");
        hm.put(1, "dog");
        System.out.println(hm.get(1)); //jack
    }
}

这段代码背后隐藏着什么呢?

节点归位,put进去,

这个数组是有大小限制的呀,如果不够的话,我们首先就想到,那就将数组扩大呗,但是,如果我是HashMap的源码的设计者,我不希望,所有节点把数组占满了之后再对它进行扩大,我觉得应该是,就像过日子嘛,节省一点,不能把东西都用光了啊,所以,我们应该要对将来有个打算啊,比如数组默认大小是16,能不能在用到12的时候就进行数组的扩大,这样我们至少是一个会打算的人,哈哈,那么我们可以引入一个<1的小数,比如0.75,数组大小用到16*0.75=12的时候,对数组进行扩大。这个小数的出现就是为了限制我们,不能等到数组全部被占用的时候再去扩大。在HashMap源码里,存在这样的小数:

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

//TREEIFY_THRESHOLD: 上文说过,如果哈希函数不合理,即使扩容也无法减少箱子中链表的长度,因此 Java 的处理方案是当链表太长时,转换成红黑树。这个值表示当某个箱子中,链表长度大于 8 时,有可能会转化成树。

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

回到我们的代码我们put一个Node节点的时候,到底是放在整个数据结构的哪里呢?

HashMap里的put()方法:

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

Node节点何去何从?应该有套规则:

hash(key)  // hash函数

来一个Node,算出一个值——大小16     肯定将该节点放到0~15之间的值的位置

我们想获取一个整数,想到Object.hashCode()会获得到一个整数,但是这个整数往往很大的,如。能不能把整数优化呢,我们要把它缩小,我们要取0~15之间的数:

        拿一个整数num%16------取余数(取模),我们肯定知道这个余数肯定在0~15之间的。

我们看源码里hash(key)函数的实现:

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

假设这里hash(key)计算会得到3254239,

真正计算这个Node节点在数组的什么位置:

实际上,这里的(n-1) & hash   ============>  hash%n   两种方式都能得到0~15之间的数值

因为,得到的hash值3254239,转化为计算机可识别的二进制1100011010011111011111,而n-1呢,n是数组大小,

默认大小是16,用二进制表示10000,n-1是15,二进制表示01111,01111&1100011010011111011111

000000000000000001111 (15)   &                                 

1100011010011111011111(3254239)

最终得到的结果,最大不过是15而已。

这里为什么不用取模操作?当然是因为&与操作在计算机里速度快,即效率高。

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

问题来了,这里数组默认16(10000),n-1是15(01111),那么假设我们默认大小是15,n-1是14(01110),那么,

000000000000000001110(14)    &                                 

1100011010011111011111(3254239)

二者做&操作的时候,结果是000000000000000001110,这样会存在问题。(自己想吧)

只有当是000000000000001111(后面全是1)这样的时候  &  通过hashcode获取到的hash值,得到的结果才真正取决于hash(key)计算出来的结果(即真正取决于我们本身的key,计算得出来的值,来得到该节点所在数据结构的位置,而不是受我们数组大小的影响),所以,我们要保证数组大小是这样的0~15,0~31,0~63......即数组大小是2的n次幂(2^n)

所以,我们看到HashMap源码里这样初始化数组:

    /**
     * The default initial capacity - MUST be a power of two.
     */
    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;

只有数组大小是2^n的时候,在后面和hash(key)的值做&操作的时候,结果才会真正取决于key。

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

hash函数的实现里,我们发现,它并不满足通过key给我们带来的hashcode值,实现里面将我们获取到key的hashcode值3254239(1100011010011111011111)向右移了16位,:

0000000000110001 1010011111011111 (低16位) ------3254239   

0000000000000000 0000000000110001(高16位)      1010011111011111(移出)

二者进行异或(^)操作,不满足的原因是什么呢?为什么还要这样折腾?

我们每次算出的key.hashcode()的值,比如key1.hashcode(),key2.hashcode()转化为二进制数之后,它们的低级位重复率比较大,结果一旦重复之后,得到的位置可能是一样的,比如都是2,那么重复的就会放到相应的下面链表里,导致链表会越来越长,链表长到一定程度的时候,这时候就会导致链表转换为红黑树,链表转红黑树非常损耗性能,所以,尽量还是使用原来这种数组+链表的方式,我们尽量让Node节点分散一点。让通过key计算出来的位置值尽可能不一样,每一个在允许范围内的位置尽可能的利用起来,此时的HashMap的利用率才是最高的。归根结底,要保证计算出来的每个key的,key.hashcode()的低级位置不让其重复,那么就通过低16位^高16位(至于为什么这样,此处未完待续),将key.hashcode()的低16位和高16位充分利用起来,这样才会使数组的利用率大大增加。

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

回顾,为什么HashMap源码的Node节点类里有hash这么样一个属性呢?

Java是一门面向对象的语言,自己的Node节点要去哪儿,自己最清楚,自己来维护。

下面我们就开始正式put:


HashMap源码里的putVal函数如下:

    /**
     * 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;
    /**
     * 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;
        if ((tab = table) == null || (n = tab.length) == 0)
            //对数组进行初始化调用resize()
            n = (tab = resize()).length;
        //判断某位置是否为空,若为空,就在创建节点并赋值给该tab[i]
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //数组的某位置不为空,就会走下面的链表
        else {
            Node<K,V> e; K k;
            //待存储在该位置的的Node节点的hash和key和在该位置上的节点的hash和key是否相同
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //相同,则覆盖该位置上的原节点
                e = p;
            //hash和key不相同,判断p节点是不是TreeNode
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //既不是对原来的值进行覆盖,也不是红黑树,就来到了链表结构
            else {
                //对链表进行循环,找到p.next为空的节点,将节点放到这个位置
                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;
                }
            }
            //如果某位置有值的话,要对其进行覆盖时,要将老值进行返回,例如,
            /**hm.put(1, "dog");
              hm.put(1, "cat");
              hm.get(1)结果返回的是dog
            */
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        //如果数组占用的数量>16*0.75,我们就resize()操作来扩容,
        //所以resize()不仅初始化数组;还有个功能就是对数组进行扩容。
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
    if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

初始化数组 

    /**
     * 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;
        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;
            }
            //对数组进行扩容的操作,例如10000<<1,就变成100000,即由16变成32;
            //同时,16*0.75也要进行扩容变成32*0.75;
            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) {
                Node<K,V> e;
                //数组j位置是否为空,不为空
                if ((e = oldTab[j]) != null) {
                    //置空
                    oldTab[j] = null;
                    //数组该位置下面没有任何,将该节点放到扩容数组里去
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    //如果该数组节点属于TreeNode节点,将红黑树打散放入新的数组,具体看split方法
                    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;
                            /**
                              oldCap是16(10000),和e.hash做&操作,判断结果是否为0
                              0000000000000000 0000000000010000
                              0100100010000010 0001010010110100
                              要想结果为0,那么hash值的第五位必须为0,
                             */
                            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;
                            //加上oldCap,即加上原来容量的位移,这里也就是指16
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

oldCap=0,执行下面这句,这句就属于对数组进行初始化: 

       else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;     //相当于16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //相当于16*0.75
        }

newThr12这个值的作用是为了告诉数组,数组大小用到了12,要进行一个扩容操作。

然后,将newThr赋值给threshold:threshold是一个全局变量int threshold;,为了记录16*0.75这样的一个值

 threshold = newThr;

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

要记录数组用了多少,这里指的是到底有没有超过12:

    /**
     * The number of key-value mappings contained in this map.
     * 包含在该映射中的键值映射的数目,这里应该指的是数组占用了多少
     */
    transient int size;

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

双倍扩容,看上面的注释......

猜你喜欢

转载自blog.csdn.net/fmsbily1/article/details/82534375