When I add data to a List
, then append that list to another list, then use List.Clear()
on the original list, it empties everything and the lists already appended aren't preserved.
Here's an example of what I'm talking about. Lets say I make 2 lists like this:
List<int> list = new List<int>();
List<List<int>> list2 = new List<List<int>>();
for(int i=0;i<10;i++){
for(int i2=0;i2<10;i2++){
list.Add(i2);
}
list2.Add(list);
list.Clear();
}
When I run list.Clear()
it clears out all of the pre-existing lists I already appended to list2
I know a work-around would be to re-arrange the code like this:
List<List<int>> list2 = new List<List<int>>();
for(int i=0;i<10;i++){
List<int> list = new List<int>(); //<- moved inside the for
for(int i2=0;i2<10;i2++){
list.Add(i2);
}
list2.Add(list);
}
But is this normal behavior? Is it possible to preserve the pre-appended lists?
The clear() method of List interface in Java is used to remove all of the elements from the List container. This method does not deleted the List container, instead it justs removes all of the elements from the List.
List<Integer> copy = new ArrayList<>(list); Integer is an immutable class; its value is set when the instance is created, and can never change.
Classes are passed by reference and List<T>
is a class. Accordingly, when you clear list it also clears the data passed by reference in list2. See List - do I pass objects or references? for more details.
This should solve the issue shown in your example and create a new copy of list
to add to list2
before clearing list
:
List<int> list = new List<int>();
List<List<int>> list2 = new List<List<int>>();
for(int i=0;i<10;i++){
for(int i2=0;i2<10;i2++){
list.Add(i2);
}
list2.Add(list.ToList()); //modified to create a new List when adding
list.Clear();
}
See also Jon Skeet's Parameter passing in C# for some broader information on how parameters are passed in C#, especially relating to reference types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With