Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在整数之间使用按位AND运算符的好处?_Java_Bitwise Operators_Bitwise And - Fatal编程技术网

Java 在整数之间使用按位AND运算符的好处?

Java 在整数之间使用按位AND运算符的好处?,java,bitwise-operators,bitwise-and,Java,Bitwise Operators,Bitwise And,我在看一些代码,如下所示: public int someMethod(String path, int maxCallers) { int hash = path.hashCode(); int caller = (hash & Integer.MAX_VALUE) % maxCallers; return caller; } 此方法根据路径返回要调用的调用方。如果maxCallers值为4,则调用者值应介于0-3之间。现在我

我在看一些代码,如下所示:

public int someMethod(String path, int maxCallers) {

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

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

你的假设是正确的。如果散列为负数,则需要删除整数的符号
使用
整数进行运算。最大值
将从整数中删除符号位。请注意,这与获取整数的绝对值不同:

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

int hash = -1;
int caller = Math.abs(hash) % 4;  // returns 1

谢谢你的回复。还有其他的方法吗?或者这是一种更快的方法?是的,这是删除符号位的最快方法。是的,我注意到,这里也没有使用Math.abs。可能正试图从Integer.MIN_值的情况下改变自己。如果hashcode是Integer.MIN\u value确实是这个值,
Math.abs
不能使用。“我能想到的一个原因是程序员想要一个正数,因为hashcode可能是负数,但我认为我在这里的理解是错误的。”你的理解实际上是正确的。这是删除标志位的最快方法。我明白了,非常感谢@dasblinkenlight