我有一个班级
class Pair<T>{
private T data;
private T alternative;
}
如果
,两对对象将是相等的this.data.equals(that.data) && this.alternative.equals(that.alternative) ||
this.data.equals(that.alternative) && this.alternative.equals(that.data)
我很难正确实现hashCode()部分。任何建议将不胜感激
答案 0 :(得分:2)
您应该使用数据和替代方案中的hashCode,如下所示:
return this.data.hashCode() + this.alterative.hashCode();
虽然这不是最好的方法,就像您更改数据或替代方案一样,但它们的哈希码也会发生变化。想一想,看看你是否真的需要将这个类用作地图中的一个键,如果不是Long或String则是一个更好的候选者。
答案 1 :(得分:1)
这应该可以解决问题:
@Override
public int hashCode() {
return data.hashCode() * alternative.hashCode();
}
由于您希望将两个字段都包含在equals中,因此需要在hashCode
方法中包含这两个字段。如果不相等的对象最终具有相同的哈希码是正确的,但根据您的方案的相同对象将始终使用此方法具有相同的哈希码。
答案 2 :(得分:0)
参考java doc,hashCode的一般契约是(从java doc复制):
- Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must
consistently return the same integer, provided no information used in
equals comparisons on the object is modified. This integer need not
remain consistent from one execution of an application to another
execution of the same application.
- If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce
the same integer result.
- It is not required that if two objects are unequal according to the
equals(java.lang.Object) method, then calling the hashCode method on
each of the two objects must produce distinct integer results.
However, the programmer should be aware that producing distinct
integer results for unequal objects may improve the performance of
hashtables.
因此,从您的equals实现,数据和替代方案可以切换。因此,如果切换data.hashCode()和alternative.hashCode()的位置,则需要确保在hashCode实现中返回相同的值。如果您不确定,只需返回一个const值,例如1(但是当您尝试将对象放入Map时,可能会导致性能问题)。