简体   繁体   中英

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" ?

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:

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. Java doesn't use reflection to "guess" the right equals and hashcode operations because knowing what the programmer intended is impossible. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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