这是反编译的 java 代码,用于将条目放入 HashMap 的方法。
/**
* Implements Map.putAll and Map constructor.
*
* @param m the map
* @param evict false when initially constructing this map, else
* true (relayed to method afterNodeInsertion).
*/
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
这个公式从何而来,它是如何工作的?
float ft = ((float)s / loadFactor) + 1.0F;
还有这个方法是什么意思
/**
* Returns a power of two size for the given target capacity.
*/
static final int tableSizeFor(int cap) {
int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
最佳答案
currentSize should <= capacity * loadFactor
, 这意味着当 currentSize / loadFactor > capacity
,我们应该调整 map 的大小。 +1
用于四舍五入。
正如它评论的那样,tableSizeFor
用于:
Returns a power of two size for the given target capacity.
关于java - resize 如何在 Java 的 Hash Map 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53706136/