wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets 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: 3410
    
  12
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparing Objects containing List
 
Similar Threads
Adding elements of two arrays
equals and Lists
exam lab gc question
equals in the case of arrays
Read file from directory, update contents of the each file