• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Comparing Objects containing List

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic