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.