I have the 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);
Now, how many objects will be in memory: 100 or 200 objects?
In the line below, are objects being added or only references?
anotherList.addAll(list);
If I make any change to list, do the same changes reflect to anotherList and vice-versa?
An object is only once in memory. Your first addition to
listjust adds the object references.anotherList.addAllwill also just add the references. So still only 100 objects in memory.If you change
listby adding/removing elements,anotherListwon’t be changed. But if you change any object inlist, then it’s content will be also changed, when accessing it fromanotherList, because the same reference is being pointed to from both lists.