Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中将一个列表插入另一个列表?_Java - Fatal编程技术网

在java中将一个列表插入另一个列表?

在java中将一个列表插入另一个列表?,java,Java,我有下面的java代码 List<SomePojo> list = new ArrayList<SomePojo>(); //add 100 SomePojo objects to list. List List=new ArrayList(); //将100个SomePojo对象添加到列表中。 现在列表中有100个对象 如果我再创建一个实例,如下所示: List<SomePojo> anotherList = new ArrayList<SomeP

我有下面的java代码

List<SomePojo> list = new ArrayList<SomePojo>();
//add 100 SomePojo objects to list.
List List=new ArrayList();
//将100个SomePojo对象添加到列表中。
现在列表中有100个对象

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

List<SomePojo> anotherList = new ArrayList<SomePojo>();
anotherList .addAll(list);
List anotherList=new ArrayList();
另一个列表。addAll(列表);

否。。。一旦您执行了另一个list.addAll(list)语句,然后如果您更改了一些列表数据,它不会携带到另一个列表中,它将保存相同的引用。因此,如果对
列表中的特定对象进行更改,将影响另一个列表中的同一对象

在任何列表中添加或删除对象都不会影响其他列表


list
另一个list
是两个不同的实例,它们只在“内部”保存对象的相同引用。

一个对象在内存中只有一次。第一次添加到
列表中
只是添加了对象引用

另一个列表.addAll
也只会添加引用。所以内存中仍然只有100个对象


如果通过添加/删除元素来更改
列表
,则不会更改另一个列表
。但是,如果您更改了
列表中的任何对象,那么当从另一个列表访问它时,它的内容也会更改,因为两个列表中指向的是相同的引用。

引用了
列表的官方javadoc。addAll

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.)

因此,您将把
列表
中对象的引用复制到
另一个列表
。任何不在
其他列表的引用对象上操作的方法(例如删除、添加、排序)都是它的本地方法,因此不会影响
列表
,摘自接口列表添加所有(集合c)Java API

将指定集合中的所有元素按指定集合的迭代器返回的顺序追加到此列表的末尾(可选操作)


您将拥有两个列表中相同数量的对象—第一个列表中的对象数量加上第二个列表中的对象数量—在您的案例中为100。

谢谢您的回复。若我在列表中添加/删除任何对象,相同的更改是否会反映到otherlist?不,不会影响。list和anotherList是两个不同的实例,它们只包含“内部”对象的相同引用。请注意,我回滚了原始问题,因为您的编辑忽略了问题本身的全部要点。问题是,这不再是一个问题,也没有任何意义;)请这个问题需要编辑,它没有意义。这个问题需要版主注意,看起来由于编辑,这个问题不再存在。如何清除或删除其他列表引用?例如,List a=new ArrayList();列表b=新的ArrayList();a、 添加(“一”);a、 添加(“两”);a、 加上(“三”),不清楚你在问什么。也许你应该在上面单独贴一个问题。