Search code examples
javahashbitwise-operators

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!


Solution

  • 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.