Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a hashcode(integer value) positive

int x = 10; int y = (x.hashcode() & 0xfffffff);

How does the above code always make y positive? Thanks!

like image 768
Siva R Avatar asked Oct 19 '15 16:10

Siva R


People also ask

How do you deal with negative hashCode?

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.

What is the hashCode of an integer?

The hashcode of an integer is the integer itself.

What is the values of a hashCode method?

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.


2 Answers

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.

like image 83
D. Kalb Avatar answered Oct 10 '22 16:10

D. Kalb


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.

like image 36
Sleiman Jneidi Avatar answered Oct 10 '22 18:10

Sleiman Jneidi