HashMap的实现

HashMap的实现

今天复习了HashMap,就和大家分享一下:


1.HashMap源码分析

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

初始化容量为1 << 4即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^30

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

默认装载因子是0.75,即在容量使用3/4是进行扩容

  • 由链表转换成树的阈值TREEIFY_THRESHOLD
   /**
     * 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;

当数组上的链表的长度大于8时,由链表转换成红黑树,这也是在jdk8中新增加的

  • 由树转换成链表的阈值UNTREEIFY_THRESHOLD
    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

当数组上的链表的长度小于6时,由红黑树转换为链表

  • MIN_TREEIFY_CAPACITY
    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

被树化时最小的hash表容量

  • put方法
    /**
     * 计算key的hash值
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    /**
     * 插入key-value
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * 实现put操作
     *
     * @param key的hash值
     * @param key值
     * @param value值
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return 之前的value
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //1. 如果当前table为空,新建默认大小的table
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //2. 获取当前key对应的节点
        if ((p = tab[i = (n - 1) & hash]) == null)
            //3. 如果不存在,新建节点
            tab[i] = newNode(hash, key, value, null);
        else {
            //4. 存在节点
            Node<K,V> e; K k;
            //5. key的hash相同,key的引用相同或者key equals,则覆盖
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //6. 如果当前节点是一个红黑树树节点,则添加树节点
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            //7. 不是红黑树节点,也不是相同节点,则表示为链表结构
            else {
                for (int binCount = 0; ; ++binCount) {
                    //8. 找到最后那个节点
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //9. 如果链表长度超过8转成红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //10.如果链表中有相同的节点,则覆盖
                    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;
                //是否替换掉value值
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //记录修改次数
        ++modCount;
        //是否超过容量,超过需要扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

猜你喜欢

转载自blog.csdn.net/qq_40422256/article/details/81675503
今日推荐