I expected to result below but actually not. I would like to know how to show the differences between two Collections. (objects are parent and child relationship) In this ca
Java collections rely on the equals
and hashCode
methods (the latter is used by HashMap
s, HashSet
s and others).
If you want to be able to use the data structure capabilities of Java collections (such as removeAll
, retainAll
etc.), you need to supply objects with proper implementations of equals
and hashCode
.
If you can't modify the Item
class, you can write a wrapper class with your own implementation of equals
:
public class ItemWrapper {
private final Item item;
public ItemWrapper(Item item) {
this.item = item;
}
public Item getItem() {
return item;
}
@Override
public boolean equals(Object obj) {
return obj instanceof ItemWrapper && item.getId().equals(((ItemWrapper) obj).item.getId());
}
@Override
public int hashCode() {
return item.getId().hashCode();
}
}
Create a new ItemWrapper
for each original Item
, store the ItemWrapper
s in Java collections, and use the required methods (removeAll
/retainAll
). Then iterate over the resulting collection and retrieve the Item
s by calling each ItemWrapper
's getItem()
method.
Your other option is to subclass ArrayList
, but it seems like a more convoluted solution.
Yet another option is not to use Java collections for the remove/retain logic, implementing them yourself instead.