2017-10-06 19 views
0

我有List<SomePojo> firstList = new ArrayList<SomePojo>();如何复制othertype列表的一个usertype列表?

// add 100 SomePojo objects to list。 现在列表中有100个对象。

如果我创建下面多了一个实例:

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

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

任何帮助,将不胜感激。

+0

'SomePojo'和'SomeOtherPojo'是否有共同界面或超类? – Fusselchen

回答

0

java.util.ArrayList.addAll(Collection c)方法将指定集合中的所有元素附加到此列表的末尾,按照指定集合的​​Iterator返回的顺序。如果指定的集合在操作正在进行时被修改,则此操作的行为是未定义的(意味着如果指定的集合是此列表且此列表非空,则此调用的行为未定义)。

firstList.addAll(anotherListObjectWhoHasSamePojoType) 
+0

我有另一个ListObjectWhoHasOtherPojoType。 – 1911192110920

+0

然后你需要定义对象类型的列表,否则你会得到异常 –

+0

然后你可以使用列表 thirdtList = new ArrayList <>; thirdList.addAll(firstlist); thirdList.addAll(secondList); –

1

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); 
+1

尼斯解释+1 – UltimateDevil

+1

谢谢@VikasTiwari –

+1

我的荣幸@NileshRathod – UltimateDevil

0

是的,有办法。

firstArrayList.addAll((ArrayList<type>) secondArrayList.clone()); 

          or 

firstArrayList.addAll((ArrayList<type>) secondArrayList); 

有关之间克隆中的addAll差异更多信息请参link

+0

编译器显示 clone()已经保护访问'java.lang.Object' – 1911192110920

0

是可能的:

secondList.addAll(firstList); 

如果SomePojo延伸SomeOtherPojo

否则你需要 - 考试ple - 通过一些简单的适配器类将SomePojo转换为SomeOtherPojo,该适配器类将“相同的公共变量”的值从SomePojo复制到SomeOtherPojo的新实例,然后将其添加到secondList。

更一般的解决方案是使用反射得到&设置这个“相同的公共变量”。