Reputation: 145
I'm having an issue understanding the output of size() for a "nested" ArrayList:
ArrayList<ArrayList<ArrayList<ArrayList<String>>>> myEmpls = new ArrayList<>();
ArrayList<ArrayList<ArrayList<String>>> dummy2 = new ArrayList<>();
ArrayList<ArrayList<String>> dummy = new ArrayList<>();
for (int x = 0; x < 4; x++) {
myEmpls.add(dummy2);
}
System.out.println(myEmpls.size());
// returns 4 as expected
System.out.println(myEmpls.get(0).size());
System.out.println(myEmpls.get(1).size());
// both return 0 as expected
for (int x = 0; x < 10; x++) {
myEmpls.get(0).add(dummy);
}
System.out.println(myEmpls.get(1).size());
// returns 10 altough I added to myEmpls.get(0) and not
// myEmpls.get(1) so I expected this to still be 0.
Can someone explain why this is the case? Maybe I am missing something obvious.
Thanks in advance.
Upvotes: 1
Views: 183
Reputation: 394026
myEmpls.add(dummy2);
add the same ArrayList
instance to myEmpls
muptiple times.
Therefore, calling myEmpls.get(0).add(dummy)
adds elements to the same ArrayList
instance referred by myEmpls.get(1)
. Therefore the size()
of myEmpls.get(1)
is 10, since myEmpls(0)==myEmpls(1)
.
If you change your first loop to :
for (int x = 0; x < 4; x++) {
dummy2 = new ArrayList<>();
myEmpls.add(dummy2);
}
each element of myEmpls
will be distinct, and myEmpls.get(1).size()
would return 0 as you expected.
Upvotes: 1
Reputation: 23012
List keeps the reference of Object
added in it,change in state of Object
reflects to all the references added in the list in your case.
ForExample :
ArrayList<List<String>> mainList =new ArrayList<>();
List<String> test1 = new ArrayList<>();
mainList.add(test1);
mainList.add(test1);
mainList.add(test1);
mainList.add(test1);
System.out.println(mainList);
test1.add("Hello");//now add item to test1
System.out.println(mainList);
OUTPUT :
[[], [], [], []]
[[Hello], [Hello], [Hello], [Hello]]
Upvotes: 1
Reputation: 5647
The reason is that you have created an ArrayList object (dummy2
) and then added that exact object to the list 4 times. Therefore, when you add to dummy
to the object from myEmpls.get(0)
, you are adding dummy to the other 3 indexes too as they are all the same object. Hence, the size is 10. Each index inside myEmpls points to exactly the same address in memory and therefore whatever you do to one of the indexes, you do to all of the others.
Upvotes: 1
Reputation: 23049
You are adding same reference of dummy2
to all four positions of myEmpls
. Therefore when you access any of them, you access same object as having variable dummy2
, which really has 10 objects in it, because you added it in it.
You can even do this and it also returns 10
System.out.println(dummy2.size());
If you do this
for (int x = 0; x < 4; x++) {
myEmpls.add(new ArrayList<ArrayList<ArrayList<String>>>());
}
It would behave as you expected
Upvotes: 3