jQuery in Action, 3rd edition
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Comparing Objects containing List" Watch "Comparing Objects containing List" New topic

Comparing Objects containing List

Samy Ganou

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>();
a1.values= arr1;

A a2 = new A();
ArrayList<String> arr2 = new ArrayList<String>();
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

Joined: Aug 05, 2005
Posts: 3742
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

I agree. Here's the link: http://aspose.com/file-tools
subject: Comparing Objects containing List
It's not a secret anymore!