0

I am trying to compare two ArrayLists, but I can't seem to get it work.

Suppose:

My main arrayList called List 1 gets its value through:

 ArrayList<xTypeClass> List1 = new ArrayList<xTypeClass>(); 
 xTypeClass tmp = new xTypeCLass();
  tmp.setName(name);
  tmp.setaddress(address);
  tmp.setPhone(phone);
  tmp.setMonth(mo);
 ..etc
 List1.add(tmp);

Now I have another list2 that holds the exact type format, but has different values. And I want to compare List2 to 1 and see which ones does not exist in List2 that does in List1 and add it to List2. I am having problem using double for loops to go around both list to find which exists and which doesn't. Can someone point me in the right direction? Comment below if you need any more information.

2 Answers2

5

Assuming you've implemented equals() and hashCode() for xTypeClass, is there any reason why you can't just do:

for (xTypeClass x : List1) {
    if (!List2.contains(x)) {
        List2.add(x);
    }
}
Dennis Meng
  • 5,109
  • 14
  • 33
  • 36
  • Thanks Dennis, this does help. Small question, There is a variable called month and a person might be listed in several months with all the other same informaiton being the same. Is there a way I can also say ignore the months set field/the variable? Thanks again. – user1452530 Jul 24 '12 at 11:54
  • Sure. equals() and hashCode() should be overridden by *you*, so you can simply just write an implementation that doesn't use the `month` field. – Dennis Meng Jul 24 '12 at 15:33
0

Throwing away list1, equals() and hashCode() implemented:

    list1.removeAll(list2); // get differnce
    list2.addAll(list1);    // add difference

If you are using eclipse then, for your xTypeClass class, you can use:

Source -> Generate hashCode() and equals...

if not using eclipse then have a look at EqualsBuilder & HashCodeBuilder from Apache Commons:

http://blog.andrewbeacock.com/2008/08/write-simpler-equals-hashcode-java.html

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Ok, so both of my arraylists have multiple attributes. What if I only want to look at 2 or 3 of them to compare with. Would this be okay? name.hashCode() ^ address.hashCode() ^ phone.hashCode(); – user1452530 Jul 24 '12 at 13:13
  • Yep, XOR is a good hashing approach http://stackoverflow.com/questions/2334218/why-are-xor-often-used-in-java-hashcode-but-another-bitwise-operators-are-used. – Reimeus Jul 24 '12 at 13:24