这对Text.hashCode()和Interger.MAX_VALUE意味着什么?

JoJ*_*oJo 5 hadoop

最近,我正在阅读hadoop的权威指南.我有两个问题:

1.我看到了一个自定义分区程序的代码:

public class KeyPartitioner extends Partitioner<TextPair, Text>{

    @Override
    public  int getPartition(TextPair key, Text value, int numPartitions){
        return (key.getFirst().hashCode()&Interger.MAX_VALUE)%numPartitions;
    }
}
Run Code Online (Sandbox Code Playgroud)

这对&Integer.MAX_VALUE意味着什么?为什么要使用&运营商?

2.我还想为IntWritable编写一个自定义分区程序.对于key.value%numPartitions,它是否可以直接?

Tho*_*lut 11

就像我在评论中写的那样,它用于保持结果整数为正.

让我们使用一个使用字符串的简单示例:

String h = "Hello I'm negative!";
int hashCode = h.hashCode();
Run Code Online (Sandbox Code Playgroud)

hashCode是负值的-1937832979.

如果您mod使用表示分区的正数(> 0),则结果数字始终为负数.

System.out.println(hashCode % 5); // yields -4
Run Code Online (Sandbox Code Playgroud)

由于分区永远不会是负数,因此您需要确保数字是正数.这里有一个简单的twiddeling技巧,因为Integer.MAX_VALUEall-one执行符号位(Java中的MSB,因为它是大端),在负数上只有1.

因此,如果您设置了符号位的负数,您将始终AND使用Integer.MAX_VALUE始终为零的零.

你可以使它更具可读性:

return Math.abs(key.getFirst().hashCode() % numPartitions);
Run Code Online (Sandbox Code Playgroud)

例如,我在Apache Hama的分区器中为任意对象做了这样的事情:

 @Override
 public int getPartition(K key, V value, int numTasks) {
    return Math.abs(key.hashCode() % numTasks);
 }
Run Code Online (Sandbox Code Playgroud)

  • 很酷的解释!+1来自我的身边. (2认同)