temp
is a reference to an ArrayList object.
ArrayList<Integer> temp;
This add the reference to the result List.
result.add(temp); // adds a copy of the reference, not a copy of the list.
This clear the original and only list (apart from the result
list)
temp.clear();
Note: Java only has references
and primitives
, there is no other types.
How could I do to avoid this situation? copy the temp list?
for every new list you want, create a new one. Instead of temp.clear() call
temp = new ArrayList<>();
Ideally, you shouldn't even reuse the local variable unless it has the same purpose.
// don't use temp again.
List<Integer> temp2 = new ArrayList<>();
BTW I advocate that you re-use mutable objects to maximise performance. You should only do this after you have measured this a problem for your allocation rate and you know what you are doing.