0

我正在查看一些代码,例如:

public int someMethod(String path, int maxCallers) {

        int hash = path.hashCode();
        int caller = (hash & Integer.MAX_VALUE) % maxCallers;
        return caller;
    }

此方法根据路径返回要调用的调用者。如果maxCallers值为 4,则调用者值应介于 0-3 之间。现在在这里我不明白 do 的用途hash & Integer.MAX_VALUE。我能想到的一个原因是程序员想要一个正数,因为哈希码可以是负数,但我认为我的理解是错误的。有人可以在这里解释按位 AND 运算符的使用。

4

1 回答 1

0

你的假设是正确的。这是在哈希为负的情况下删除整数的符号。ANDing withInteger.MAX_VALUE将从整数中删除符号位。请注意,这与获取整数的绝对值不同:

int hash = -1;
int caller = (hash & Integer.MAX_VALUE) % 4;  // returns 3

int hash = -1;
int caller = Math.abs(hash) % 4;  // returns 1
于 2015-01-24T10:03:00.980 回答