int x = 10; int y = (x.hashcode() & 0xfffffff);
How does the above code always make y
positive? Thanks!
Negative hashcode is perfectly valid! It is perfectly legal to have negative hash codes, and if you are looking for hash values as used in hash-based collections you can use Math. abs(hash) . This can also give you negative numbers when hash is bigger than 2^31, and the best way would be to use a shift mask (key.
The hashcode of an integer is the integer itself.
The Java hashCode() Method hashCode in Java is a function that returns the hashcode value of an object on calling. It returns an integer or a 4 bytes value which is generated by the hashing algorithm.
The &
will perform a bitwise AND operation. 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 bits are set to 1
, the result will be a 1
, 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, 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
.
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 something you want.
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.
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