我有List< SomePojo > firstList = new ArrayList< SomePojo >();
//将 100 个 SomePojo 对象添加到列表中。 现在列表中有 100 个对象。
如果我再创建一个实例,如下所示:
List<SomeOtherPojo> secondList = new ArrayList<SomeOtherPojo>();
这里,SomePojo 和 SomeOtherPojo 内部具有相同的公共(public)变量。 如何将firstList的内容复制到secondList? 有什么办法可以做到吗?
如有任何帮助,我们将不胜感激。
最佳答案
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);
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/