我正在尝试编写自定义 hashCode fn,但我无法找出正确的方法。
public class Person {
String name;
List<String> attributes;
@Override
public boolean equals(Object o) {
// Persons are equal if name is equal & if >= 2 of attributes are equal
// This I have implemented
}
@Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = (result*PRIME) + (this.name == null ? 0 : this.name.hashCode());
//Not sure what to do here to account for attributes
return result;
}
}
我希望 hashCode fn 是这样的:
“如果根据 equals() 方法,object1 和 object2 相等,则它们也必须具有相同的哈希码”
不知道该怎么做?
最佳答案
如Oli points out in the comments ,您无法通过实现 equals()
并依靠 Set
来为您消除重复来解决此问题。奇怪的事情可能会发生。
因此您必须自己编写代码。将列表中的第一项添加到新的重复数据删除列表中。然后,对于原始列表中的每个剩余项目,将其与已删除重复列表中的项目进行比较,只有在通过非重复测试时才添加它。
关于java - 使用列表的一部分进行比较时的自定义 hashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25322859/