Java – the problem of implementing removeAll for a custom object list
There is a scenario in my code where I need to compare two lists and delete the objects in the second list from the first list Similar to how a "removeAll" object works for a list Because my list is created on a custom object, the removeAll method has no effect on me
I've tried various ways to do this: – implement equals () and hashcode for custom objects containing lists – implement comparable interface for custom objects – implement comparator interface for custom objects
I even tried to use Apache common's collectionutils and listutils methods (subtract, cross, delete all) There seems to be no job
I know I may need to write some custom deletion code But I don't know how to do it Any instructions that help me move in the right direction will be appreciated
Thank you, Jay
Solution
Java collections are already suitable for your scenario Call collection RemoveAll (Collection), which will use the equals () method to remove all entries from the incoming collection to test equality
List<String> list1 = new ArrayList<String>(); Collections.addAll(list1,"one","two","three","four"); List<String> list2 = new ArrayList<String>(); Collections.addAll(list2,"four","five"); list1.removeAll(list2); // Now contains "one","two"
In order to make this work, the object you are storing only needs to correctly implement the equals / hashcode contract, that is, given any two objects a and B:
a.equals(b) == b.equals(a)
And:
a.hashCode() == b.hashCode() if a.equals(b)
Incorrectly defined equals and hashcode methods produce undefined behavior and are a common cause of collection related problems