Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with implementing removeAll for List of custom object

I have a scenario in my code where I need to compare two Lists and remove from the first list, objects which are present in the second list. Akin to how the "removeAll" object works for List. Since my List is created on a custom object, the removeAll method won't work for me.

I have tried various methods to make this work: - implemented equals() and hashCode for the custom object comprising the list - implemented the Comparable Interface for the custom object - implemented the Comparator Interface for the custom object

I've even tried using the Apache Common's CollectionUtils and ListUtils methods (subtract, intersect, removeAll). None seem to work.

I understand I will perhaps need to write some custom removal code. But not sure how to go about doing that. Any pointers helping me move in the right direction will be really appreciated.

Thanks, Jay

like image 673
Jay Avatar asked Apr 11 '10 14:04

Jay


2 Answers

Java Collections already cater for your scenario. Call Collection.removeAll(Collection) and it'll remove all the items from the passed in collection using the equals() method to test for equality.

List<String> list1 = new ArrayList<String>();
Collections.addAll(list1, "one", "two", "three", "four");
List<String> list2 = new ArrayList<String>();
Collections.addAll(list2, "three", "four", "five");
list1.removeAll(list2); // now contains "one", "two"

To make this work the objects you're storing just need to properly implement the equals/hashCode contract, which is: given any two objects a and b:

a.equals(b) == b.equals(a)

and:

a.hashCode() == b.hashCode() if a.equals(b)

Improperly defined equals and hashCode methods create undefined behaviour and are the common cause of collections related issues.

like image 94
cletus Avatar answered Oct 06 '22 00:10

cletus


Overriding equals and hashCode methods is enough to make method removeAll work on custom objects.

It's likely that you didn't override them in a proper way. Some code will help us a lot.

like image 22
Roman Avatar answered Oct 05 '22 23:10

Roman