java - 消除 bin 索引计算中的循环

标签 java algorithm

这是一个implementation of HashMap .

它提供了用于获取垃圾箱索引的代码:

private int getIndex(K key)
{
    int hash = key.hashCode() % nodes.length;
    if (hash < 0)
        hash += nodes.length;
    return hash;
}

To make sure the hash value is not bigger than the size of the table, the result of the user provided hash function is used modulo the length of the table. We need the index to be non-negative, but the modulus operator (%) will return a negative number if the left operand (the hash value) is negative, so we have to test for it and make it non-negative.

如果hash结果是很大的负值,则循环中的加法hash +=nodes.length可能需要大量处理。

我认为应该有一个O(1)算法(独立于哈希值)。

如果可以,如何实现?

最佳答案

它不能是一个很大的负数。

anything %nodes.length 的结果绝对值始终小于 nodes.length,因此您需要一个 if,不是循环。这正是代码的作用:

if (hash < 0) /* `if', not `while' */
    hash += nodes.length;

关于java - 消除 bin 索引计算中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13601834/

相关文章:

Java媒体框架: how do I install JMF for mac?

java - 如何构建良好的 Java GUI 应用程序设计模式?

java - 如何从 StepExecutionListener afterStep 方法停止 Spring Batch 作业?

java - 在 OOP 中使用太多单例和静态方法会有什么风险?

angularjs - BackboneJS 和 AngularJS 排序稳定吗?

algorithm - 查找所有 1's in a matrix having 1' 和 0 的最大尺寸子矩阵

python - 快速放置拼图位的方法

java - 在 Java 8 中将 Map 中的值转换为 List<Serialized>

algorithm - 什么算法时间复杂度高,求助 "burn"多CPU周期?

algorithm - 如何保持动态直方图?