Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting one list into another list in java? [closed]

Tags:

java

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); 
like image 873
user1016403 Avatar asked Jun 30 '12 10:06

user1016403


People also ask

Can we add a list to another list in Java?

It is possible to add all elements from one Java List into another List . You do so using the List addAll() method.

How do I add a list of values to a list in Java?

ArrayList<List<String>> keyHold = new ArrayList<List<String>>(); String cold[] = new String[]{"actions","cold","enabled"}; List<String> lCold = Arrays. asList(cold); lCold. add(Rows. getRow(rowNum, 0)); keyHold.


2 Answers

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.

like image 68
MicSim Avatar answered Oct 07 '22 20:10

MicSim


100, it will hold the same references. Therefore if you make a change to a specific object in the list, it will affect the same object in anotherList.

Adding or removing objects in any of the list will not affect the other.

list and anotherList are two different instances, they only hold the same references of the objects "inside" them.

like image 41
setzamora Avatar answered Oct 07 '22 20:10

setzamora