简体   繁体   中英

Is this a good implementation of hashCode()?

I have a class that will be used in a HashSet . It only contains two members, and both are of the same type interface. This is what it looks like:

class MyClass{
    MyInterface a;
    MyInterface b;

    public int hashCode(){
         return a.hashCode() + b.hashCode();
    }

    public boolean equals(Object obj){
         if(!(obj instanceof MyClass)
              return false;
         MyClass other (MyClass) obj;
         return (this.a == other.a && this.b == other.b) || (this.a == other.b && this.b == other.a);
    }
}

As you can see, two instances of MyClass are "equal" if they contain the same two instances of MyInterface .

Now, I was thinking that for hashCode() , I could just add up the default hashcodes of its members. Is this good enough? If not, what is a proper implementation of hashCode() for this case?

Yes, this is perfectly fine. It's equivalent to the implementation of Set.hashCode() for two-element sets.

I would say no. Wouldn't this mean that these two instances of MyClass would hash to the same value:

MyClass {
  a.hashCode = 2;
  b.hashCode = 3;
}

and

MyClass {
  a.hashCode = 1;
  b.hashCode = 4;
}

Yes it is.

Because even with hashCode collision, the docs state :

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.

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