How to make a hashcode(integer value) positive

谁都会走 提交于 2020-01-24 03:47:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!