I've tried to create a program with 2 lists; list1 (List<Integer>
), that would constantly add new values, and list2 (List<List<Integer>>
), that would store values of list1. I've started with this:
int x=1;
while(x<=10)
{
list1.add(x);
System.out.println(list1);
x++;
}
And output was just like i thought;
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
then I've changed System.out.println(list1);
to list2.add(list1);
and then included an enchanced for loop;
for(List<Integer> y:list2)
{
System.out.println(y);
}
But instead of the output like before, it said:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Like it just repeated the last state of list1 10 times! Do you know, what is the reason?
Because you add the integers to the same List
object at each iteration, and then add this list object to your list of list object.
Think of a situation like this :
One workaround could be :
int x=1;
while(x <= 10){
l1 = new ArrayList<>(l1);//create a new list object with values of the old one
l1.add(x);
l2.add(l1);
x++;
}
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