我有一个大约有 450 个字段的 POJO,我正在尝试使用 hascode 来比较此 POJO 的实例。我已经用 eclipse 生成了重写的 hashCode()
方法。在相当多的情况下,生成的哈希码会跨越整数边界。结果,进行比较变得困难。解决方法是什么?
hashCode()
方法如下:
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((stringOne == null) ? 0 : stringOne.hashCode());
result = prime * result + intOne;
result = prime * result + Arrays.hashCode(someArray);
result = prime * result + ((stringTwo == null) ? 0 : stringTwo.hashCode());
result = prime * result + intTwo;
result = prime * result + intThree;
result = prime * result + ((stringThree == null) ? 0 : stringThree.hashCode());
result = prime * result + ((stringFour == null) ? 0 : stringFour.hashCode());
result = prime * result + ((stringFive == null) ? 0 : stringFive.hashCode());
result = prime * result + ((objectOne == null) ? 0 : objectOne.hashCode());
result = prime * result + ((objectTwo == null) ? 0 : objectTwo.hashCode());
return result;
}
最佳答案
整数溢出是 hashCode()
计算的正常部分。这不是问题。
例如,String
的 hashCode()
通常为负数。
System.out.println("The hashCode() of this String is negative".hashCode());
如果 hashCode()
计算可能会溢出,显然这可能意味着不相等的 Object
可以具有相同的 hashCode
,但这可以发生没有溢出。例如,这两个都打印 true
。
System.out.println("Aa".hashCode() == "BB".hashCode());
System.out.println(new HashSet<>(Arrays.asList(1, 2)).hashCode() == Collections.singleton(3).hashCode());
唯一的要求是相同的对象应该具有相同的hashCode
。不要求不同的对象应具有不同的 hashCode
。
hashCode()
和 equals()
也应该很快。您可以通过首先比较最有可能不同的字段并尽早返回来提高 equals()
的性能。您无法使用 hashCode()
执行此操作,因为计算必须涉及所有相关字段。如果您的类有 450 个字段,您可能需要考虑缓存 hashCode()
的结果,或者更好的方法是将您的类重构为更小的单元。
要考虑的另一件事是您是否需要重写这些方法。仅当对象要用作基于哈希的容器(例如 HashMap
)中的键时,这是绝对必要的。
关于java - 哈希码跨越整数边界时的解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32584128/