且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将一个列表插入到Java中的另一个列表中?

更新时间:2023-02-01 16:54:24

对象在内存中只有一次.您对 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.