【JAVA秒会技术之秒杀面试官】集合篇(二)

来源:互联网 发布:达内java培优班知乎 编辑:程序博客网 时间:2024/04/30 17:28

秒杀Java面试官——集合篇(二)

三、HashMap底层实现原理(基于JDK1.8)

        面试中,你是否也曾被问过以下问题呢:

    你知道HashMap的数据结构吗?HashMap是如何实现存储的?底层采用了什么算法?为什么采用这种算法?如何对HashMap进行优化?如果HashMap的大小超过了负载因子定义的容量,怎么办?等等。

    有觉得很难吗?别怕!下面博主就带着大家深度剖析,以源代码为依据,逐一分析,看看HashMap到底是怎么玩的:

       ① HashMap源码片段 —— 总体介绍:  

/* Hash table based implementation of the<tt>Map</tt> interfaceHashMap实现了Map接口. This implementation provides all of the optional map operations, and permits <tt>null</tt> values and the<tt>null</tt> key允许储存null值和null键.  (The <tt>HashMap</tt> class is roughly equivalent to<tt>Hashtable</tt>, except that it is unsynchronized and permits nulls.(HashTable和HashMap很相似,除了HashTable的方法是同步的,并且不允许储存null值和null键))  This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time(HashMap不保证映射的顺序,特别是它不保证该顺序不随时间变化).*/

       ② HashMap源码片段 —— 六大初始化参数:

    /**     * 初始容量1 << 4 = 16     */    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;     /**     * 最大容量1 << 30 = 1073741824     */    static final int MAXIMUM_CAPACITY = 1 << 30;    /**     * 默认负载因子0.75f     */    static final float DEFAULT_LOAD_FACTOR = 0.75f;    /**     * 由链表转换成树的阈值:即当bucket(桶)中bin(箱子)的数量超过     * TREEIFY_THRESHOLD时使用树来代替链表。默认值是8      */    static final int TREEIFY_THRESHOLD = 8;    /**     * 由树转换成链表的阈值:当执行resize操作时,当bucket中bin的数量少于此值,     * 时使用链表来代替树。默认值是6      */    static final int UNTREEIFY_THRESHOLD = 6;    /**     * 树的最小容量     */    static final int MIN_TREEIFY_CAPACITY = 64;

        ③ HashMap源码片段 —— 内部结构:

    /**     * Basic hash bin node, used for most entries.      */    // Node是单向链表,它实现了Map.Entry接口    static class Node<K,V> implements Map.Entry<K,V> {        final int hash;   // 键对应的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;        }    // 存储(位桶)的数组</k,v>transient Node<K,V>[] table;    // 红黑树    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {        TreeNode<K,V> parent; // 父节点        TreeNode<K,V> left;    // 左节点        TreeNode<K,V> right;   // 右节点        TreeNode<K,V> prev;    // needed to unlink next upon deletion        boolean red;             // 颜色属性        TreeNode(int hash, K key, V val, Node<K,V> next) {            super(hash, key, val, next);        }

      简单看:JDK1.8中,HashMap采用位桶+链表+红黑树实现。具体实现原理,我们继续看源码。关于红黑树,我将在后期《算法篇》详细介绍。

      ④ HashMap源码片段 —— 数组Node[]位置:

    // 第一步:先计算key对应的Hash值    static final int hash(Object key) {        int h;        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}
    // 第二步:保证哈希表散列均匀    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;}

★对第二步的作用,进行简要说明(很高级!):

{ 可以从源码看出,在HashMap的构造函数中,都直接或间接的调用了tableSizeFor函数。下面分析原因:length2的整数幂保证了length-1最后一位(当然是二进制表示)为1,从而保证了取索引操作h&length-1)的最后一位同时有为0和为1的可能性,保证了散列的均匀性。反过来讲,当length为奇数时,length-1最后一位为0,这样与h按位与的最后一位肯定为0,即索引位置肯定是偶数,这样数组的奇数位置全部没有放置元素,浪费了大量空间。简而言之:length2的幂保证了按位与最后一位的有效性,使哈希表散列更均匀。}

// 第三步:计算索引:index = (tab.length - 1) & hash    if (tab == null || (n = tab.length) == 0) return;int index = (n - 1) & hash;

  (区别于HashTable :index = (hash &0x7FFFFFFF) % tab.length;

取模中的除法运算效率很低,但是HashMap的位运算效率很高)

       ⑤ HashMap源码片段 —— 常用get()/put()操作:

    /**     * Implements Map.get and related methods     *     * @param hash hash for key     * @param key the key     * @return the node, or null if none     */    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 &&             //tab[(n - 1) & hash]得到对象的保存位            (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) {                //判断:如果第一个节点是TreeNode,则采用红黑树处理冲突                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;    }    /**     * 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)            //如果tab为空或长度为0,则分配内存resize()            n = (tab = resize()).length;        if ((p = tab[i = (n - 1) & hash]) == null)            //tab[i = (n - 1) & hash]找到put位置,如果为空,则直接put            tab[i] = newNode(hash, key, value, null);        else {            Node<K,V> e; K k;             //先判断key的hash()方法判断,再调用equals()方法判断            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) {                    //p第一次指向表头,之后依次后移                    if ((e = p.next) == null) {                        //e为空,表示已到表尾也没有找到key值相同节点,则新建节点                        p.next = newNode(hash, key, value, null);                        //新增节点后如果节点个数到达阈值,则将链表转换为红黑树                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st                            treeifyBin(tab, hash);                        break;                    }                    //允许存储null键null值                    if (e.hash == hash &&                        ((k = e.key) == key || (key != null && key.equals(k))))                        break;                    //指针下移一位                    p = e;                }            }            //更新hash值和key值均相同的节点Value值            if (e != null) { // existing mapping for key                V oldValue = e.value;                if (!onlyIfAbsent || oldValue == null)                    e.value = value;                afterNodeAccess(e);                return oldValue;            }        }        ++modCount;        if (++size > threshold)            resize();        afterNodeInsertion(evict);        return null;    }

        ⑥ HashMap源码片段 —— 扩容resize():

    //可用来初始化HashMap大小 或重新调整HashMap大小 变为原来2倍大小    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; // 扩容阈值加倍        }        else if (oldThr > 0)  // oldCap=0 ,oldThr>0此时newThr=0             newCap = oldThr;        else {   // oldCap=0,oldThr=0 相当于使用默认填充比和初始容量 初始化            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) {                                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,初始容量为16实际容量 = 初始容量*负载因子(默认0.75) = 12

        ②调用put方法,会先计算key的hash值:hash = key.hashCode()。

        ③调用tableSizeFor()方法,保证哈希表散列均匀

        ④计算Nodes[index]的索引:先进行index = (tab.length - 1) & hash

        ⑤如果索引位为null,直接创建新节点,如果不为null,再判断所因为上是否有元素

        ⑥如果有:则先调用hash()方法判断,再调用equals()方法进行判断,如果都相同则直接用新的Value覆盖旧的;

        ⑦如果不同,再判断第一个节点类型是否为树节点(涉及到:链表转换成树的阈值,默认8),如果是,则按照红黑树的算法进行存储;如果不是,则按照链表存储;

       ⑧当存储元素过多时,需要进行扩容

   默认的负载因子是0.75,如果实际元素所占容量占分配容量的75%时就要扩容了。大约变为原来的2倍newThr =oldThr << 1);

0 0
原创粉丝点击