How to use Collections methods(removeAll() and retainAll()) for two objects. (objects are parent-child relation)

后端 未结 1 587
情书的邮戳
情书的邮戳 2020-12-18 08:44

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

相关标签:
1条回答
  • 2020-12-18 08:52

    Java collections rely on the equals and hashCode methods (the latter is used by HashMaps, HashSets 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 ItemWrappers in Java collections, and use the required methods (removeAll/retainAll). Then iterate over the resulting collection and retrieve the Items 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.

    0 讨论(0)
提交回复
热议问题