java - HashMap 调整其表的大小

标签 java hashmap

我知道 HashMap 的大小默认为 16,我们还可以为其提供一些其他值。如果我将大小初始化为 5,负载因子为 0.8f,然后将第五个元素添加到它会增长到 10 还是 16?一旦非 2 的幂值发生阈值突破,它会跳到 2 的幂吗?

最佳答案

最好看看 source code :

 final Node<K,V>[]  [More ...] resize() {      
         Node<K,V>[] oldTab = table;  
         int oldCap = (oldTab == null) ? 0 : oldTab.length;
         int oldThr = threshold;
         int newCap, newThr = 0;   
         if (oldCap > 0) {   
             if (oldCap >= MAXIMUM_CAPACITY) {   
                 threshold = Integer.MAX_VALUE;   
                 return oldTab;    
             }    
             else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&   
                      oldCap >= DEFAULT_INITIAL_CAPACITY)    
                 newThr = oldThr << 1; // double threshold    
         }    
         else if (oldThr > 0) // initial capacity was placed in threshold    
             newCap = oldThr;
         ...
         // The capacity of the inner data structure is doubled
         Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
         table = newTab;
         ...

因此,调整大小后当前容量和阈值将加倍。

但是,构造一个初始容量不是2的幂的HashMap对象是不可能的!构造函数将初始容量转换为2的幂:

static final int tableSizeFor(int cap) {
     int n = cap - 1;
     n |= n >>> 1;
     n |= n >>> 2;
     n |= n >>> 4;
     n |= n >>> 8;
     n |= n >>> 16;
     return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY: n + 1;
 }

public  [More ...] HashMap(int initialCapacity, float loadFactor) {
     ...
     this.loadFactor = loadFactor;
     this.threshold = tableSizeFor(initialCapacity);
}

关于java - HashMap 调整其表的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43339264/

相关文章:

java - 避免多个对象事务死锁的最佳方法?

java - 如何从命令行运行单个 gradle 任务

hashmap - 是否可以创建一个由 `HashMap` 类型的键控的 `*const Any` ?

amazon-web-services - 从ES中删除字段

java - 如何解决android中的这个hashmap逻辑错误?

java.util.TimeZone DST 问题

java Swing : in paintComponent method how to know what to repaint?

java - 该程序的 KeyAdapter 部分出错

java - Java HashMap 中的 ConcurentModificationException

java - 如何使用文本文件中的键值创建 HashMap?