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 can assert that the two Set s are equal to one another, which invokes the Set equals() method. This @Test will pass if the two Set s are the same size and contain the same elements.
assertEquals. public static void assertEquals(Object expected, Object actual) Asserts that two objects are equal. If they are not, an AssertionError without a message is thrown. If expected and actual are null , they are considered equal.
Using JUnit We can use the logic below to compare the equality of two lists using the assertTrue and assertFalse methods. In this first test, the size of both lists is compared before we check if the elements in both lists are the same. As both of these conditions return true, our test will pass.
assertEquals. Asserts that two object arrays are equal. If they are not, an AssertionError is thrown with the given message. If expecteds and actuals are null , they are considered equal.
You're not overriding hashCode()
, which means the default implementation will be used. HashSet
checks for matching hash codes first, before calling equals
- that's how it manages to find potential matches so efficiently. (It's easy to "bucket" an integer.)
Basically, you need to override hashCode
in a manner which is consistent with your equals
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With