我有一个类,其相等性基于 2 个字段,因此如果其中一个字段相等,则此类型的对象被视为相等。如何为这样的 equals() 编写 hashCode() 函数,以便在 equals 返回 true 时保留 hashCode 的一般合同?
public class MyClass {
int id;
String name;
public boolean equals(Object o) {
if (!(o instanceof MyClass))
return false;
MyClass other = (MyClass) o;
if (other.id == this.id || other.name == this.name)
return true;
return false;
}
}
我如何为这个类编写一个 hashCode() 函数?我想避免像这样返回一个常量的微不足道的情况:
public int hashCode() {
return 1;
}