HashMap

作者: 每天进步一丢儿丢儿 | 来源:发表于2020-06-01 16:04 被阅读0次
  • hashmap的初始容量是 1<< 4 即2的4次方16
  • hashmap的最大容量是 1 <<30 即2的30次方
  • hashmap的默认负载因子 0.75f
  • hashmap的扩容触发机制,当hashmap中的存储的数据节点的数量大于hashmap的容量与负载因子的乘积,即此时的扩容阈值的话就会触发扩容。还有一种情况也会触发扩容,即当一个hash桶中的链表长度大于8时会触发扩容机制。hash桶中的链表形成原因是由于hash函数计算结果产生碰撞造成的,hashmap对于hash碰撞的解决方案是分离链表法。还有一种解决hash碰撞的方案是线性探测法。
  • hashmap红黑树化的触发条件是当某一个hash桶的hash碰撞次数超过8次的时候就会触发当前hash桶链表的树化(红黑树)。
  • hashmap的存储接口是复杂的,其树化并不是针对所有的hash桶实现,只针对当某一个hash桶的链表长度大于8时的链表进行树化,所以其内部的存储结构会同时存在数组,链表,红黑树。
 /**
     * 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) {
        // n 标识表长度,i 标识索引
        Node<K,V>[] tab; Node<K,V> p; int n, i;
       // 如果空表
        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;
            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) {
                    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;
    }

相关文章

网友评论

      本文标题:HashMap

      本文链接:https://www.haomeiwen.com/subject/bshoahtx.html