【发布时间】:2022-12-12 20:14:51
【问题描述】:
我有一个 Foo 类,它具有很好覆盖的 hashCode、equals 方法和定义明确的 compareTo 方法。
class Foo {
@Override
public int hashCode() {
// Well-define hashCode method
}
@Override
public boolean equals(Object other) {
// Well-define equals method
}
public int compareTo(OtherClass other) {
// Well-defined compareTo method
}
}
然后我有另一个班级 MyClass 覆盖了 hashCode 和 equals 方法。
class MyClass {
int myValue;
List<Foo> myList;
@Override
public int hashCode() {
// Is this a good hashCode method?
myList.sort(Foo::compareTo);
return Objects.hash(myValue, myList);
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass())
return false;
MyClass otherMyClass = (MyClass) other;
if (myValue != otherMyClass.myValue)
return false;
myList.sort(Foo::compareTo);
otherMyClass.myList.sort(Foo::compareTo);
return myList.equals(otherMyClass.myList);
}
}
我知道如果两个对象相等,那么它们的哈希值也必须相等,而 MyClass 的 hashCode 方法就是这样做的。但我不确定我的方法是否是一个好的哈希生成器。是吗?
PS:排序myList是个好主意,还是我应该使用排序后的副本进行比较? myList 的顺序与MyClass 无关。
【问题讨论】:
-
我个人永远不会期望 hashcode 或 equals 方法来修改对象。所以我不认为在 hashcode 或 equals 方法中对列表进行排序是个好主意。如果您想确保列表中元素的顺序不影响 equals/hashcode 方法,您应该创建这些列表的副本并对副本进行排序,但保持原件不变。
-
@OHGODSPIDERS 说得通。谢谢!