Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java using Lists to store Lists

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?

like image 719
Atom Avatar asked Feb 14 '23 15:02

Atom


1 Answers

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 :

enter image description here 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++;
}
like image 99
Alexis C. Avatar answered Feb 17 '23 10:02

Alexis C.