HashMap原理探究

5 篇文章 0 订阅

HashMap原理探究


hashMap 原理简单来讲就是,数组链表,一个数组下装的是一个Node链表。

几个关键字解释

  1. DEFAULT_INITIAL_CAPACITY (默认容量)1 << 4 (16),必须是2的次幂;
  2. loadFactor(默认负载因子):默认0.75,设置扩容阀值用
  3. threshold (扩容阀值):初始的时候是 默认的负载因子大小 * 默认的初始容量大小
  4. TREEIFY_THRESHOLD (树优化阀值):默认是 8,当数组队列大于该值时,改用红黑树进行优化(treeifyBin(tab, hash);)。

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    
    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (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;
    
    /**
     * The load factor for the hash table.
     *
     * @serial
     */
    final float loadFactor;
    
    /**
     * 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;

几个关键方法解读

  • final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)
  • final Node<K,V>[] resize()
  • static final int hash(Object key)

putVal

put方法源码 + 解读:

    /**
     * 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就是一个数组(可以想象成一个桶),如果是空的,resize()进行赋初值
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            // 如果key值相等,则替换原来的value
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果已经变成红黑树的数据结构则使用红黑树的put方法
            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);
                return oldValue;
            }
        }
        ++modCount;
        // 如果数值大于阀值,则进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

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;
        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;
            }
            // 扩容,容器容量和阀值都乘以2
            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;
        // 扩容新建一个Node
        @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;
                            // 确定是否保持放在原来的数组下,还是放在扩容或的数组下
                            // 如:(16) 0001 0000 & 
                            //     (15) 0001 1111  -> 扩容前就在1111桶下,扩容过后& =0 也放在原来的位置
                            //        = 0000 0000
                            
                            // 但,原来的链表需要重新放置的:
                            // 如:(16) 0001 0000 & 
                            //     (27) 0001 1011 -> 扩容前就在1011桶下(& 1111=1011)
                            //     = 0001 0000,所以这个链表需要重新放置
                            // 放置的位置就是 原来的位置+oldCap (1011 -> 1 1011)
                            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;
    }

hash方法

hash方法源码 + 解读:

    /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        // 低16位与高16位异或,得到一个全新的32位hash值,加大了低位的随机性,减少hash碰撞(扰动函数)
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

几个问题

Q: resize方法(e.hash & oldCap) = 0 的含义?

A: 如果 e.hash & oldCap = 0 的话,说明 e.hash是 oldCap 的范围内的。为什么这么说那,因为假设oldCap大小是16,那么16的二进制是:0001 0000;e.hash = 15 : 0000 1111; 16 & 15 = 0 ,也就是说,&之后的结果取决于16二进制中的 1 ,所以这些元素还是放在原来的数组内。但是如果原来是在该数组内的元素hash,例如:0001 1111,那么这个元素会从该数组移动到 数组下标+oldCap 数组里。为什么那?计算下就知道了,如果大小是16的话,那么应该放到的就是1111这个数组下标里,扩容成32的话,就变 1 1111 的了,把原来的元素,移动到了扩容后计算应该到的数组下。

Q: Hashmap为什么大小是2的次幂?

A: 当hashMap的容量为2的次幂时,hashMap的效率最高。假如hashMap大小为15,那么下标最大为14,& 上 hash 值,那么得到的值永远是0结尾,那么0001,0011,0101,1001,1011,0111,1101这几个位置永远都不能存放元素了,空间浪费大,这种情况下,数组可以用的长度大大减小,增加了碰撞几率。减小了查询效率。所以,hashMap在选值时,只能选转化为二进制后,最低位是 1 的数,也就是说长度只能为偶数(减一后变奇数)。那么为什么选2的次幂而不选20、14这种长度那?如果是20,那么就是 & 上19 (10011),那么,可以看出中间那两个0永远不会为1,那么对应的数字永远不会轮到,所以这里可以得到一个结论:为了使得每个数字都能 & 出得到(减少碰撞,达到取模的效果),二进制数必须全是1,满足这个条件的就只能是:(2 的次幂-1),而这样的数值,在与hash值进行 & 操作,使得高位全部为0,低位在0到容量长度间取值(取决于hash的低位)。

Q: 为减少hash碰撞,hashMap做了哪些处理?

A: 其实为了避免hash碰撞,可以对容量大小取模,但是取模效率太低,所以采用了 & 的方式,同时长度取2的次幂(具体看上一个问答)。还有就是在取hash值时使用 扰动函数,也就是将 hash出来的值,将高16位与低16位进行异或(XOR),以此来加大低位的随机性,减少hash碰撞

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值