Reputation:
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?
Upvotes: 4
Views: 147
Reputation: 2824
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;
}
Upvotes: 1
Reputation: 13349
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.
Upvotes: 0
Reputation: 198014
Yes, this is perfectly fine. It's equivalent to the implementation of Set.hashCode()
for two-element sets.
Upvotes: 3