简体   繁体   English

如何为两个对象使用Collections方法(removeAll()和retainAll())。 (对象是父子关系)

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

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 case, can I use standard method like removeAll() or can you recommend another approach like using apache-commons. (对象是父子关系)在这种情况下,我可以使用像removeAll()这样的标准方法,还是可以推荐另一种方法,比如使用apache-commons。 Thanks. 谢谢。

CONSTRAINT
------------------------------
1.Item.class is unmodifiable(eg. I can not add equals method)
2.If id is same between two objects, they are assumed as same things.
------------------------------

EXPECTED
------------------------------
removed object are:
2
same object are:
1
3
add object are:
4
------------------------------

ACTUAL
------------------------------
removed object are:
1
2
3
same object are:
add object are:
1
3
4
------------------------------

package com.javastudy;

import java.util.ArrayList;
import java.util.List;

public class CollectionCompareToObjects {

    public static void main(String[] args) {

        List<Item> before = new ArrayList<Item>();
        List<ItemEx> after = new ArrayList<ItemEx>();

        before.add(new Item(1L));
        before.add(new Item(2L)); // delete
        before.add(new Item(3L));

        after.add(new ItemEx(1L));
        after.add(new ItemEx(3L));
        after.add(new ItemEx(4L)); // added

        List<Item> removed = new ArrayList<Item>(before);
        removed.removeAll(after);

        System.out.println("removed objects are:");
        for(Item item : removed){
            System.out.println(item.getId());
        }

        List<Item> same = new ArrayList<Item>(before);
        same.retainAll(after);

        System.out.println("same objects are:");
        for(Item item : same){
            System.out.println(item.getId());
        }

        List<Item> added = new ArrayList<Item>(after);
        added.removeAll(before);

        System.out.println("add objects are:");
        for(Item item : added){
            System.out.println(item.getId());
        }

    }

}


package com.javastudy;

public class Item {

    private Long id;

    public Item(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}

package com.javastudy;

public class ItemEx extends Item {

    private String name;

    public ItemEx(Long id) {
        super(id);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Java collections rely on the equals and hashCode methods (the latter is used by HashMap s, HashSet s and others). Java集合依赖于equalshashCode方法(后者由HashMapHashSet和其他人使用)。

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 . 如果您希望能够使用Java集合的数据结构功能(例如removeAllretainAll等),则需要为对象提供equalshashCode正确实现。

If you can't modify the Item class, you can write a wrapper class with your own implementation of equals : 如果你不能修改Item类,你可以用你自己的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 ). 为每个原始Item创建一个新的ItemWrapper ,将ItemWrapper存储在Java集合中,并使用所需的方法( removeAll / retainAll )。 Then iterate over the resulting collection and retrieve the Item s by calling each ItemWrapper 's getItem() method. 然后迭代生成的集合并通过调用每个ItemWrappergetItem()方法来检索Item

Your other option is to subclass ArrayList , but it seems like a more convoluted solution. 你的另一个选择是继承ArrayList ,但它似乎是一个更复杂的解决方案。

Yet another option is not to use Java collections for the remove/retain logic, implementing them yourself instead. 另一个选择是不要将Java集合用于删除/保留逻辑,而是自己实现它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何对两个对象使用Collections方法(removeAll()和retainAll()) - How to use Collections methods(removeAll() and retainAll()) for two objects 两个对象之间的父子关系导致 JSON StackOverflowError - Parent-child relation between two objects causes JSON StackOverflowError 级联删除具有父子关系的对象到同一表的麻烦 - Troubles with cascade deleting objects with parent-child relations to the same table 实例化对象和子/父​​类的关系 - Instantiating Objects & the relation of Child/Parent classes 在Spring Data JPA中保留两个不同模式之间具有父子关系的表 - Persist Tables with parent-child relation between two different schema in Spring Data JPA 在子类中如何使用在父类中创建的对象? - How to use objects created in Parent class inside Child class? 使用 Java 流 API 创建具有父子结构的嵌套对象集合? - Creating nested collection of objects with parent-child structure using Java Streams API? ArrayList removeAll() 不删除对象 - ArrayList removeAll() not removing objects JPA-如何在不构造父对象的情况下构造ManyToOne关系的子对象 - JPA - How to construct child objects of a ManyToOne relation without constructing the parent object removeAll()不会删除对象 - removeAll() is not removing objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM