如果“第一个”和“第二个”交换,我希望 Pair 类的两个实例被视为相等,即 Pair(1,2) == Pair(2,1) 应该评估为 true。
static class Pair {
int first;
int second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Pair that = (Pair) obj;
return (this.first == that.first && this.second == that.second)
|| (this.second == that.first && this.first == that.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second) + Objects.hash(second, first);
}
}
Run Code Online (Sandbox Code Playgroud)
我想出了这个 hashcode(),它似乎有效,但是有没有更好/普遍接受的方法来做到这一点?
没有开销的更简单的哈希码Objects.hash()是:
@Override
public int hashCode() {
return first + second;
}
Run Code Online (Sandbox Code Playgroud)
它与Integer.hashCode()返回Integer值类似。
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |