aspose file tools*
The moose likes Java in General and the fly likes Comparing Objects containing List Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Comparing Objects containing List" Watch "Comparing Objects containing List" New topic
Author

Comparing Objects containing List

Samy Ganou
Greenhorn

Joined: Oct 05, 2009
Posts: 28
I have a class :
class A {
public List<String> values;
}
I want to compare two instances .

A a1 = new A();
ArrayList<String> arr1 = new ArrayList<String>();
arr1.add("1");
arr1.add("2");
a1.values= arr1;

A a2 = new A();
ArrayList<String> arr2 = new ArrayList<String>();
arr2.add("1");
arr2.add("2");
a2.values= arr2;

a1 and a2 are equals but a2.equals(a1) give me false !
how i can compare ?
thank you in advance.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3658
    
  15
Your A class does not override the equals method, therefore it inherits it from the Object class, which means that a1.equals(a2) is exactly the same as a1 == a2. i.e. it will only be true if a1 and a2 refer to the same object, which in this case they don't.
You need to override equals and return the result of comparing the two lists


Joanne
 
jQuery in Action, 2nd edition
 
subject: Comparing Objects containing List