【发布时间】:2014-07-10 01:06:52
【问题描述】:
例如,我的班级看起来像下面的班级。在 equals() 中,我定义了一个等价,其中两个 id 之一(或两者)相等会导致整个 MyObject.equals() 方法返回 true。不管这是一件好事(我已经为一个项目放弃了这种方法),我很好奇是否可以定义一个可以与等号正确工作的 hashCode() 方法() 方法。
public class MyObject {
private UUID id;
private UUID secondaryId;
public MyObject(UUID id, UUID secondaryId) {
this.id = id;
this.secondaryId = secondaryId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyObject myObject = (MyObject) o;
// Both id and secondary Id are not null on both objects
if (id != null && myObject.id != null && secondaryId != null &&
myObject.secondaryId != null) {
return id.equals(myObject.id) &&
secondaryId.equals(myObject.secondaryId);
}
// Id is not null on both objects
else if (id != null && myObject.id != null) {
return id.equals(myObject.id);
}
// Secondary id is not null on both objects
else if (secondaryId != null && myObject.secondaryId != null) {
return secondaryId.equals(myObject.secondaryId);
}
return false;
}
@Override
public int hashCode() {
// TODO: How do write a hashcode that reflects the equals method?
}
}
从我对这种方式的一点想法来看,这似乎很难做到,因为您可能总是会丢失数据。当您尝试将一个具有两个 id 定义的对象与一个定义了一个 id 的对象匹配时,我不知道您将如何知道真相。我能想出的最佳答案是,如果您总是有一个定义了 both id 的对象,您可以创建一个哈希,它是两个键的两个 16 位哈希的组合他们之间有一个标记。因此,您总是会查看第一个 id 的前 16 位,然后查看第二个 id 的下 16 位。也就是说 - 我不知道如何用 Java 这样的语言编写这种方法。
TLDR; 你会如何编写 hashCode() 方法?
【问题讨论】:
-
你的
.equals不是传递的:MyObject(A,null)==MyObject(A,B)==MyObject(null,B),而是MyObject(A,null)!=MyObject(null,B)。 -
return 0;适用于 anyequals。
标签: java hash computer-science hashcode