Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java assertEquals sets

Tags:

java

assert

set

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?

like image 670
Razvan Avatar asked Sep 04 '12 10:09

Razvan


People also ask

How do you assert sets in java?

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.

What is assertEquals in java?

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.

How do you use assertEquals with a list?

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.

Does assertEquals work on arrays?

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.


1 Answers

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.

like image 179
Jon Skeet Avatar answered Sep 26 '22 09:09

Jon Skeet