问题
int x = 10; int y = (x.hashcode() & 0xfffffff);
How does the above code always make y
positive? Thanks!
回答1:
x.hashcode() & 0xfffffff
will turn the sign bit off. Math.abs
is not used here because it returns negative if x.hashCode
is equal to Integer.MIN_VALUE
which will make the hashtable's
array throw an ArrayOutOfBoundException
which is not fun.
From @JonSkeet comment: It doesn't just turn the sign bit off, it clears the next three bits as well.
But with hash codes we deal with collisions all the time, so it is considered fine.
回答2:
The &
will perform a bitwise AND comparison. That means it will take the bits of the first number, in your case the hashcode, and the second number, in your case 0xFFFFFFF
and will compare them. If both compared bits are set to 1
, the rsult will be a one, else it will be 0
.
To give you short example: if we perform this comparison between 1011
and 1100
, the result would be 1000
because just the left bit is 1
for both numbers. Coming back to 0xFFFFFFF
, the binary presentation of this number is consisting of just 28 bits. An integer like the one returned by the hashfunction is consisting of 32 bits.
If you now perform a bitwise AND comparison, the left 4 bits are ignored because 0xFFFFFFF
is missing the first 4 bits and therefore they filled with zeros and the result of the comparison will be 0
. The rest stays the same since there is always a one in the second number. The first bit is used to indicate whether the number is positive or negative and this value gets lost. So it's set to 0
and therefore the whole number is positive.
The disadvantage here is that the following three bits are also lost. If you want to keep them, you would have to set the first number to 0
and the rest to 1
, so instead of 0xFFFFFFF
you would use 0x7FFFFFFF
.
来源:https://stackoverflow.com/questions/33219638/how-to-make-a-hashcodeinteger-value-positive