简体   繁体   中英

Correct implementation of hashcode/equals

I have a class

class Pair<T>{
    private T data;
    private T alternative;
}

Two pair objects would be equal if

this.data.equals(that.data) && this.alternative.equals(that.alternative) || 
this.data.equals(that.alternative) && this.alternative.equals(that.data)

I'm having difficulty correctly implementing the hashCode() part though. Any suggestions would be appreciated

You should use the hashCode from data and alternative like this :

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

Although it is not the best approach, as if you change the data or alternative, then their hashcode will also change. Think a little bit and see if you really need to use this class as a key in a map and if not a Long or String would be a better candidate.

This should do the trick:

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

Since you want to include both fields into the equals, you need to include both fields into the hashCode method. It is correct if unequal objects end up having the same hash code, but equal objects according to your scheme will always end up having the same hash code with this method.

Refer to the java doc, the general contract of hashCode is(copied from 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.

So from your implementation of equals, data and alternative are switchable. So you need make sure in your hashCode implementation returns the same value if you switch the position of data.hashCode() and alternative.hashCode(). If you are not sure, just return a const value such as 1 (But it may cause performance issue when you try to put the object into a Map).

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