将一个列表添加到java中的另一个列表? [英] Adding one list to another list in java?
问题描述
我有以下java代码。
I have below java code.
List<SomePojo> list = new ArrayList<SomePojo>();
//add 100 SomePojo objects to list.
现在列表有100个对象。
Now list has 100 objects.
如果我再创建一个实例,如下所示:
If i create one more instance as below:
List<SomePojo> anotherList = new ArrayList<SomePojo>();
anotherList .addAll(list);
谢谢!
推荐答案
对象在内存中只有一次。您首次添加列表
只会添加对象引用。
An object is only once in memory. Your first addition to list
just adds the object references.
anotherList.addAll
也将只添加引用。所以内存中只有100个对象。
anotherList.addAll
will also just add the references. So still only 100 objects in memory.
如果通过添加/删除元素更改 list
, anotherList
不会被更改。但是如果你更改 list
中的任何对象,那么当从 anotherList
访问它时,它的内容也会被更改,因为两个清单都指出了相同的参考。
If you change list
by adding/removing elements, anotherList
won't be changed. But if you change any object in list
, then it's content will be also changed, when accessing it from anotherList
, because the same reference is being pointed to from both lists.
这篇关于将一个列表添加到java中的另一个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!