我有以下两个类,想使用 Foo1
作为 HashMap
中的键。两个 Foo1
对象如果它们的 Foo2
对象相等则相等,而 Foo2
对象如果它们的字节数组满足 Arrays.equals( )
。
我不太确定如何处理 Foo1
的 hashCode()
方法。我是否只需要总结其每个 Foo2
对象的哈希码,还是效率低下?
public class Foo1 {
Foo2[] foo2_array;
@Override
public boolean equals(Object Other) {
for (int i = 0; i < foo2_array.length; i++) {
if (!foo2_array[i].equals(other.foo2_array[i])
return false;
}
return true;
}
@Override
public int hashCode() {
// what to here?
}
}
public class Foo2 {
byte[] values;
@Override
public boolean equals(Object other) {
return Arrays.equals(values, other.values);
}
@Override
public int hashCode() {
return Arrays.hashCode(values);
}
}
最佳答案
您的 hashcode
应该使用与 equals
相同的属性集,以免破坏契约。
只需使用 Arrays.hashcode
,就像在 Foo2
中所做的那样
此外,您不必遍历 equals 中的每个元素,您只需使用 Arrays.equals
Foo2 equals 看起来像这样类似于 Foo1.equals
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Foo1 other = (Foo1) obj;
if (!Arrays.equals(foo2_array, other.foo2_array))
return false;
return true;
}
和类似于Foo1 hashcode的hashcode
@Override
public int hashCode() {
return Arrays.hashCode(foo2_array);
}
此外,在实现 equals 时,还要检查相同的引用和对象是否为 null 的有效性。
关于java - hashCode() 用于在 HashMap 中使用的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10748481/