java - 如何将一种用户类型的列表复制到其他类型的列表?

标签 java android arraylist

我有List< SomePojo > firstList = new ArrayList< SomePojo >();

//将 100 个 SomePojo 对象添加到列表中。 现在列表中有 100 个对象。

如果我再创建一个实例,如下所示:

List<SomeOtherPojo> secondList = new ArrayList<SomeOtherPojo>();

这里,SomePojo 和 SomeOtherPojo 内部具有相同的公共(public)变量。 如何将firstList的内容复制到secondList? 有什么办法可以做到吗?

如有任何帮助,我们将不胜感激。

最佳答案

1.使用Collections.copy()

Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected.

 public static <T> void copy(List<? super T> dest,
                List<? extends T> src)

Parameters:

dest - The destination list.

src - The source list.

Throws:

IndexOutOfBoundsException - if the destination list is too small to contain the entire source List.

UnsupportedOperationException - if the destination list's list-iterator does not support the set operation.

示例代码

List< SomePojo > firstList = new ArrayList< SomePojo >();
List< SomeOtherPojo > secondList = new ArrayList< SomeOtherPojo >(firstList.size());

Collections.copy(secondList,firstList);

2.使用ArrayList.addAll();

It adds all the elements of specified Collection c to the current list. Adds all of the specified elements to the specified collection.

ArrayList<ChatDataModel> firstList = new ArrayList<>();
firstList.add(model);
firstList.add(model4);
firstList.add(model2);
firstList.add(model3);
ArrayList<ChatDataModel> secondList = new ArrayList<>(firstList.size());
secondList.addAll(firstList);

关于java - 如何将一种用户类型的列表复制到其他类型的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598722/

相关文章:

java - 没有参数和默认构造函数混淆

Android Facebook SDK 导入出现错误 - Eclipse

java - 如何将 ArrayList<String> 发送到另一个 Activity 并在那里显示?

android - ArrayList<Object> 使用 getSerialized 问题到第二个 Activity

java - 计算两个 Java 日期实例之间的差异

java - GWT 应用程序是否受益于 session 集群?

java - 让 selenium 独立服务器与 phpunit 一起使用时出现问题

java - 如何在Android中从URL加载不带文件扩展名的图像到ImageView

android - 如何通过 SDK Manager 安装旧版本的 Android?

java - Android 填充 ArrayList 时的性能问题