HashMap最大容量为什么是2的32次方

╰+攻爆jí腚メ 2022-08-21 08:00 296阅读 0赞
  1. //默认的桶数组大小
  2. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
  3. //极限值(超过这个值就将threshold修改为Integer.MAX_VALUE(此时桶大小已经是2的31次方了),表明不进行扩容了)
  4. static final int MAXIMUM_CAPACITY = 1 << 30;
  5. //负载因子(请阅读下面体会这个值的用处)
  6. static final float DEFAULT_LOAD_FACTOR = 0.75f;

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

  1. void resize(int newCapacity) {
  2. Entry[] oldTable = table;
  3. int oldCapacity = oldTable.length;
  4. if (oldCapacity == MAXIMUM_CAPACITY) {
  5. threshold = Integer.MAX_VALUE;//将threshold置为Integer.MAX_VALUE
  6. return;//当HashMap的容量已经是2的31次方的时候,直接返回。
  7. }
  8. Entry[] newTable = new Entry[newCapacity];
  9. transfer(newTable);
  10. table = newTable;
  11. threshold = (int)(newCapacity * loadFactor);
  12. }

观察jdk中源码可发现当HashMap的容量已经是2的31次方的时候,就不会在进行扩容了。

  1. /** * The next size value at which to resize (capacity * load factor). * @serial */
  2. int threshold;

如上为对threshold的定义。

  1. /**
  2. * Adds a new entry with the specified key, value and hash code to
  3. * the specified bucket. It is the responsibility of this
  4. * method to resize the table if appropriate.
  5. *
  6. * Subclass overrides this to alter the behavior of put method.
  7. */
  8. void addEntry(int hash, K key, V value, int bucketIndex) {
  9. Entry<K,V> e = table[bucketIndex];
  10. table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
  11. if (size++ >= threshold)
  12. resize(2 * table.length);
  13. }

观察如上源码可知,当添加完元素后的容量大于threshold,就调用resize方法。

发表评论

表情:
评论列表 (有 0 条评论,296人围观)

还没有评论,来说两句吧...

相关阅读