繁体   English   中英

正确实现哈希码/等号

[英]Correct implementation of hashcode/equals

我有一堂课

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()部分方面遇到困难。 任何建议,将不胜感激

您应该使用数据中的hashCode和类似的替代方法:

  return this.data.hashCode() + this.alterative.hashCode();

尽管这不是最佳方法,但是就像您更改数据或替代方法一样,它们的哈希码也会更改。 仔细考虑一下,看看您是否真的需要将此类用作映射中的键,如果不是,则最好使用Long或String。

这应该可以解决问题:

  @Override
  public int hashCode() {
    return data.hashCode() * alternative.hashCode();
  }

由于要将两个字段都包含在等号中,因此需要将两个字段都包含在hashCode方法中。 如果不相等的对象最终具有相同的哈希码是正确的,但是根据您的方案,相等的对象将始终使用此方法最终具有相同的哈希码。

参考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.

因此,从实现等式开始,数据和替代项都是可切换的。 因此,如果切换data.hashCode()和Alternative.hashCode()的位置,则需要确保在hashCode实现中返回相同的值。 如果不确定,则只返回一个const值,例如1(但是当您尝试将对象放入Map中时,可能会导致性能问题)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM