Skip to main content
added 256 characters in body
Source Link
Eran
  • 395.1k
  • 57
  • 726
  • 793

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.

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).

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.

Source Link
Eran
  • 395.1k
  • 57
  • 726
  • 793

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).