I have two sets:
Set<Attribute> set1 = new HashSet<Attribute>(5);
Set<Attribute> set2 = new HashSet<Attribute>(5);
//add 5 attribute objects to each of them. (not necessarily the same objects)
assertEquals(set1,set2); //<--- returns false, even though
//the added attribute objects are equal
The equals method of Attribute is overridden, according to my requirements:
public abstract class Attribute implements Serializable{
public int attribute;
public abstract boolean isNumerical();
@Override
public boolean equals(Object other){
if(!(other instanceof Attribute)){
return false;
}
Attribute otherAttribute = (Attribute)other;
return (this.attribute == otherAttribute.attribute &&
this.isNumerical() == otherAttribute.isNumerical());
}
}
when debugging, the equals method is not even called!
Any ideas?
You’re not overriding
hashCode(), which means the default implementation will be used.HashSetchecks for matching hash codes first, before callingequals– that’s how it manages to find potential matches so efficiently. (It’s easy to “bucket” an integer.)Basically, you need to override
hashCodein a manner which is consistent with yourequalsmethod.