HashMap源码解读

2018-08-26 17:19:13来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折




/**
     * 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

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:写给自己的面试题--从各处搜罗过来的

下一篇:最课程学员启示录:一份有诚意的检讨书