In Java, I encountered the following line:
e.g.: (1 & Integer.MAX_VALUE) % 4
e.g.: (2 & Integer.MAX_VALUE) % 5
What does it do? I have tried the code, but I couldn't comprehend its purpose or functionality. What is the code trying to check?
Basically, it's (int & Integer.MAX_VALUE) % int
.
Actual code (from Hadoop training class):
public int getPartition(StringPairWritable key, Text value, int numReduceTasks) {
return (key.getLeft().hashCode() & Integer.MAX_VALUE) % numReduceTasks;
}
i & Integer.MAX_VALUE
does the same thing as this code:
if(i < 0) {
i = (i + Integer.MAX_VALUE + 1);
}
The %
is a regular remainder operation.
It's a quick way of ensuring that an integer is positive if you don't care about it's actual value (e.g. if you want to turn random numbers that can be both positive and negative into only positive values).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With