简体   繁体   English

HashCodeBuilder的用法,以及如何以及为什么为具有字段的对象计算Java hashCode?

[英]HashCodeBuilder use, and How and Why are Java hashCode computed for objects with fields?

I am sure there is a good reason, but could you kindly explain why .equals() and .hashCode() do not use reflection to just "work" ? 我敢肯定有一个很好的理由,但是您能否请您解释一下为什么.equals()和.hashCode()不使用反射只是“工作”?

For example in: 例如在:

class Test {      
  Integer x = 1, y = 2;
}

Test t1 = new Test();
Test t2 = new Test();
System.out.println(t1.equals(t2)); // returns false
System.out.println(t1.hashCode() == t2.hashCode()); // returns false

I am using HashCodeBuilder and EqualsBuilder to get consistent hashes of simple objects, as in: 我正在使用HashCodeBuilder和EqualsBuilder来获得简单对象的一致哈希,如下所示:

class Test {      
  Integer x = 1, y = 2;

  @Override
  public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
  }

  @Override
  public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
  }
}

Test t1 = new Test();
Test t2 = new Test();
System.out.println(t1.equals(t2)); // returns true
System.out.println(t1.hashCode() == t2.hashCode()); // returns true

Could you comment on whether this is the right way to do it? 您能否评论这是否是正确的方法?

HashCodeBuilder and EqualsBuilders are not part of the JDK, they are features of the Apache Commons Lang project. HashCodeBuilder和EqualsBuilders不是JDK的一部分,它们是Apache Commons Lang项目的功能。 Java doesn't use reflection to "guess" the right equals and hashcode operations because knowing what the programmer intended is impossible. Java不使用反射来“猜测”正确的等号和哈希码操作,因为知道程序员的意图是不可能的。 By default, objects do have a default hashcode and equals method (which is why you are overriding them), and each object has a pseudo-unique hashcode and is only equal to itself. 默认情况下,对象确实具有默认的哈希码和equals方法(这就是您覆盖它们的原因),并且每个对象都有一个伪唯一的哈希码,并且仅与自身相等。

In some programs, it may be correct to have equality and hashcodes unique to each individual object, rather than reflectively inspecting the fields at runtime. 在某些程序中,使每个对象具有唯一性的相等性和哈希码,而不是在运行时反思检查字段可能是正确的。 In other programs, programmers may which to disregard certain fields and have equality and hashcode only operate on a subset of an objects fields. 在其他程序中,忽略某些字段并具有相等性和哈希码的程序员可能只对对象字段的子集进行操作。 There are infinitely many possibilities and combinations of fields that a programmer might intend or not intend to use for equality, which is why Java makes the safest assumption and makes each object equal only to itself. 程序员可能打算或不希望使用许多可能性和字段组合来实现相等性,这就是Java做出最安全的假设并使每个对象仅与自身相等的原因。

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

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