java - resize 如何在 Java 的 Hash Map 中工作?

标签 java algorithm hash hashmap

这是反编译的 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/

相关文章:

java - MySQL语法错误异常 : Unknown column xxx in 'field list'

python - 如何解决此错误 : Py4JJavaError: An error occurred while calling o70. showString?

python - 找到与另外 2 个点共线的 3d 点

php - 为什么Heap的算法会出现重复

algorithm - 查找字符串中的所有字谜 O(n) 解决方案

java - 使用线程测试 GAE 数据存储

JAVA:Stripe Webhook 错误:未找到与有效负载的预期签名匹配的签名

java - 具有公差级别的 double 哈希方法

出现提示时,使用 OpenSSL 的 Facebook SDK 的 Android key 哈希生成未设置为 android

c - 字符串的哈希函数