将一个列表添加到java中的另一个列表?
我有以下java代码。
List list = new ArrayList(); //add 100 SomePojo objects to list.
现在列表有100个对象。
如果我再创建一个实例,如下所示:
List anotherList = new ArrayList(); anotherList .addAll(list);
谢谢!
对象在内存中只有一次。 您对list
首次添加只会添加对象引用。
anotherList.addAll
也将只添加引用。 所以内存中只有100个对象。
如果通过添加/删除元素来更改list
,则不会更改anotherList
。 但是如果你更改list
任何对象,那么当从anotherList
访问它时,它的内容也会被更改,因为两个列表都指向相同的引用。
100,它将保持相同的参考。 因此,如果对list
的特定对象进行更改,则会影响anotherList
的同一对象。
添加或删除任何列表中的对象不会影响另一个。
list
和anotherList
是两个不同的实例,它们只保存对象“内部”的相同引用。
引用List.addAll
的官方javadoc:
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation). The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (Note that this will occur if the specified collection is this list, and it's nonempty.)
因此,您将list
对象的引用复制到anotherList
。 任何不对anotherList
的引用对象进行操作的方法(例如删除,添加,排序)都是本地的,因此不会影响list
。
接口列表中的 addAll(集合c)的Java API摘录, 请参见此处
“将指定集合中的所有元素追加到此列表的末尾,按指定集合的迭代器(可选操作)返回它们的顺序。”
在两个列表中,您将拥有尽可能多的对象 – 第一个列表中的对象数量加上第二个列表中的对象数量 – 在您的情况下为100。
不…一旦你执行了语句anotherList.addAll(list),之后如果你改变了一些列表数据,它就不会携带到另一个列表