问题描述
我有下面的Java代码.
List< SomePojo>list = new ArrayList< SomePojo>();//将100个SomePojo对象添加到列表中.
现在列表中有100个对象.
如果我再创建一个实例,如下所示:
List< SomePojo>anotherList = new ArrayList< SomePojo>();anotherList .addAll(list);
对象在内存中只有一次.您对 list
的第一次添加只是添加了对象引用.
anotherList.addAll
也将仅添加引用.因此内存中仍然只有100个对象.
如果您通过添加/删除元素来更改列表
,则不会更改 otherList
.但是,如果您更改 list
中的任何对象,那么从 anotherList
中访问它时,它的内容也将被更改,因为从两个列表中都指向相同的引用./p>
I have below java code.
List<SomePojo> list = new ArrayList<SomePojo>();
//add 100 SomePojo objects to list.
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
will also just add the references. So still only 100 objects in memory.
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中的另一个列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!