Cratylus
Cratylus

Reputation: 54094

Comparing lists in JUnit. It succeeds but I have not override equals. How does it work?

I have a class with primitive fields like the following:

public class Person{  
  String name;  
  int age;  
  int id;  
  int height;  
  public Person(String name, int age, int id, int height){  
      this.name = name;
      this.age = age;  
      this.id = id;  
      this.height = height;  
  } 
  //other methods
}  

I have various persons that I want to sort by age:

Person p87 = new Person("John", 87, 123, 185);  
Person p22 = new Person("George", 22, 12, 180);  
//etc  ....for other persons. Then I create a list of them
List<Person> persons= Arrays.asList(p87, p22, p45, p31, p55, p62 );  
Collections.sort(persons, new Comparator<Person>() {

            @Override
            public int compare(Person p1, person p2) {
                return p1.age - p2.age;
            }

        });   

Now I want to test if it has been sorted correctly so I have a JUnit test case with the following:

assertEquals(Arrays.asList(p22, p31, p45, p55, p62, p87 ), persons);

The testcase passes. So it is sorted.
But I don't understand this. The assertEquals would compare the 2 lists using the List.equals which calls the equals on each contained object.
The problem is that I have not override equals in the class Person.
As a result the following fails:

Person p22 = new Person("George", 22, 12, 180);   
Person p22_2 = new Person("George", 22, 12, 180);    
assertEquals(p22, p22_2);  

I don't understand this. Why then the 2 list passed as equal in the test case?

Upvotes: 2

Views: 539

Answers (1)

Mark Byers
Mark Byers

Reputation: 839114

In your first example you aren't creating new objects - you are comparing references to the same object. This works because the default implementation of equals is to compare for reference equality.

You are doing the equivalent of this:

Person p22 = new Person("George", 22, 12, 180);   
Person p22_2 = p22;
assertEquals(p22, p22_2);   // works, because both refer to the same object

Upvotes: 7

Related Questions