How to make hashcode (integer value) positive

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

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

+5
source share
1 answer

x.hashcode() & 0xfffffff will disable the sign. Math.abs is not used here because it returns negative if x.hashCode is Integer.MIN_VALUE , which will make the hashtable's array ArrayOutOfBoundException , which is not funny.

From @JonSkeet's comment: it does not just turn off the sign, it also clears the next three bits.

But with hash codes, we deal with collisions all the time, so it's considered great.

+10
source

Source: https://habr.com/ru/post/1234042/


All Articles