1
java.util.List<java.util.List<String>> statuses = new java.util.ArrayList<>();
java.util.List<String> temp = new java.util.ArrayList<>();

System.out.println("yoi :" + temp.size());
statuses.add(temp);
System.out.println("warui :" + statuses.get(0).size());
temp.clear();
System.out.println("kirai :" + statuses.get(0).size());

Console output:

yoi :31
warui :31
kirai :0

Why on earth list inside other list becames empty when I clear temporary list that I used to insert it?

Haruki
  • 109
  • 1
  • 10

3 Answers3

5

You are adding a reference to a List to your statuses List, which means statuses holds a reference to the same List referenced by temp.

You should create a copy of temp before adding it to the List:

statuses.add(new ArrayList<>(temp));

Now clearing temp won't affect statuses.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Oh I never dealt with list nested inside other lists, I thought it passes value and not reference. thanks it worked! ^^ – Haruki Nov 08 '17 at 11:20
  • @Haruki it passes a value, but that value is a reference. – Eran Nov 08 '17 at 11:21
1

When you put temp into statuses, there will not be a copy made of temp, but only the reference will be set.

So either working with temp directly or working with statuses.get(0) will always return you the same instance. Every modification is on the same object.

Korashen
  • 2,144
  • 2
  • 18
  • 28
-1

You are actually displaying the size of temp in your 3rd println. Try

System.out.println("kirai :" + statuses.size());
  • I understand now that it uses temp by reference, but I dont use: statuses.size() instead because I want to check size of inserted list inside and not an amount of lists in statuses. – Haruki Nov 08 '17 at 11:22
  • oh sorry, passig parameters by reference is so obvious to me that I did not realize it was your problem, sorry :) – ThePoltergeist Nov 08 '17 at 11:24
  • It is no problem, I fixed it :) – Haruki Nov 08 '17 at 11:34