简体   繁体   English

addAll 函数正在复制 List 中的对象

[英]addAll function is duplicating objects in List

My goal is to join two lists in one list, but the problem is that the objects of the first list duplicates twice, this the code below:我的目标是在一个列表中加入两个列表,但问题是第一个列表的对象重复两次,这是下面的代码:

List<Image> unionList = new ArrayList<Image>();

      unionList.addAll(fromImageList);

       unionList.addAll(fromTagList);

so that the objects of fromImageList are joined twice.以便 fromImageList 的对象连接两次。

If you want aggregate only unique images, then you should use Set如果你只想聚合唯一的图像,那么你应该使用 Set

Set<Image> uniqueImages = new HashSet<>();

uniqueImages.addAll(fromImageList);

uniqueImages.addAll(fromTagList);

List<Image> unionList = new ArrayList<>(uniqueImages)

When List<Image> unionList = new ArrayList<Image>();List<Image> unionList = new ArrayList<Image>(); is excecuted, an empty arrayList is created.被执行,一个空的arrayList被创建。

When unionList.addAll(fromImageList);unionList.addAll(fromImageList); is excecuted, all the images in fromImageList are added to unionList.执行后,fromImageList 中的所有图像都添加到 unionList 中。

When unionList.addAll(fromTagList);unionList.addAll(fromTagList); is excecuted, all the images in fromTagList are added to unionList.执行后,fromTagList 中的所有图像都添加到 unionList 中。

ArrayList doen't prevent duplication. ArrayList 不能防止重复。 If you want to prevent duplication, you have to use Set implementation like HashSet.如果你想防止重复,你必须使用像 HashSet 这样的 Set 实现。

You can do like the following您可以执行以下操作

Set<Image> uniqueImages = new HashSet<>();
uniqueImages.addAll(fromImageList);
uniqueImages.addAll(fromTagList);

List<Image> unionList = new ArrayList<>(uniqueImages)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM