本文介绍了如何使哈希码(整数值)为正值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

上面的代码如何使y总是正值?谢谢!

How above code makes y is always positive? Thanks!

推荐答案

x.hashcode()& 0xfffffff 会关闭符号位。如果 x.hashCode 等于,则 Math.abs Integer.MIN_VALUE 这将使哈希表的数组抛出一个 ArrayOutOfBoundException ,这并不好玩。

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.

来自@JonSkeet评论:它不会仅仅关闭符号位,它还会清除接下来的三位

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.

这篇关于如何使哈希码(整数值)为正值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:33