zoukankan      html  css  js  c++  java
  • HashMap最大容量为什么是2的32次方

    1
    2
    3
    4
    5
    6
    观察jdk中HashMap的源码,我们知道极限值为2的31次方。

    void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
    threshold = Integer.MAX_VALUE;//将threshold置为Integer.MAX_VALUE
    return;//当HashMap的容量已经是2的31次方的时候,直接返回。
    }

    Entry[] newTable = new Entry[newCapacity];
    transfer(newTable);
    table = newTable;
    threshold = (int)(newCapacity * loadFactor);
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    观察jdk中源码可发现当HashMap的容量已经是2的31次方的时候,就不会在进行扩容了。

    /**
    * The next size value at which to resize (capacity * load factor).
    * @serial
    */
    int threshold;
    1
    2
    3
    4
    5
    如上为对threshold的定义。

    /**
    * Adds a new entry with the specified key, value and hash code to
    * the specified bucket. It is the responsibility of this
    * method to resize the table if appropriate.
    *
    * Subclass overrides this to alter the behavior of put method.
    */
    void addEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
    if (size++ >= threshold)
    resize(2 * table.length);
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    观察如上源码可知,当添加完元素后的容量大于threshold,就调用resize方法。
    ---------------------
    作者:liudezhicsdn
    来源:CSDN
    原文:https://blog.csdn.net/liudezhicsdn/article/details/51234292?utm_source=copy
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    CentOS7 FTP安装与配置
    linux CentOS 安装 nginx
    linux CentOS YUM 安装 nginx+tomcat+java+mysql运行环境
    Node.js 开发
    Nginx 负载均衡
    BtxCMS.Net 项目
    不得不看!史上最全的三十多张架构师图谱!
    高危群体:开发者的自白,躲坑,迷茫,和下一步
    p2p-如何拯救k8s镜像分发的阿喀琉斯之踵
    Tower与DevCloud对比分析报告
  • 原文地址:https://www.cnblogs.com/ExMan/p/9800041.html
Copyright © 2011-2022 走看看