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 Answers 2

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Sure. equals() and hashCode() should be overridden by you, so you can simply just write an implementation that doesn't use the month field.
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

2 Comments

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();
Yep, XOR is a good hashing approach stackoverflow.com/questions/2334218/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.