• HashMap源码解读





    /**
         * The default initial capacity - MUST be a power of two.
       * 解释:为了节省空间和让元素均匀分布,所以初始化容量,需要为2的乘方。
         */
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    
         /**
          * 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.
         * 解释:当一个桶中的元素个数达到8个时候就要,数据存储的数据结构就由链表变为了红黑树
         */
        static final int TREEIFY_THRESHOLD = 8;
    
        /**
         * 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;

     Q&A:

    1. 为什么变成红黑树是8,而转化成链表是6?

      有人从源码分析,有人从查找时间复杂度分析。部分源码如下:

     * Because TreeNodes are about twice the size of regular nodes, we
         * use them only when bins contain enough nodes to warrant use
         * (see TREEIFY_THRESHOLD). And when they become too small (due to
         * removal or resizing) they are converted back to plain bins.  In
         * usages with well-distributed user hashCodes, tree bins are
         * rarely used.  Ideally, under random hashCodes, the frequency of
         * nodes in bins follows a Poisson distribution
         * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
         * parameter of about 0.5 on average for the default resizing
         * threshold of 0.75, although with a large variance because of
         * resizing granularity. Ignoring variance, the expected
         * occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
         * factorial(k)). The first values are:
         *
         * 0:    0.60653066
         * 1:    0.30326533
         * 2:    0.07581633
         * 3:    0.01263606
         * 4:    0.00157952
         * 5:    0.00015795
         * 6:    0.00001316
         * 7:    0.00000094
         * 8:    0.00000006
         * more: less than 1 in ten million
    */

    2. 容量为什么是2的乘方呢?https://blog.csdn.net/sd_csdn_scy/article/details/57083619

  • 相关阅读:
    EL表达式取整问题
    win7下安装 oracle 10g:permission denied
    jsp引用servlet生成的验证码..
    控制span的width属性
    Spring读书笔记Spring的Bean之设置Bean值
    如何将WEBINF下的jsp页面插入在frameset中
    一友人说有急事要回家,看发生何事
    占淘宝,今日无空,留存
    一人占工作调动
    代码恶心度判定法则
  • 原文地址:https://www.cnblogs.com/lvmengtian/p/9531318.html
Copyright © 2020-2023  润新知