Kamila - 27 days ago 7
Java Question

# List of List in for loops Java

I have problem. I try to do develop
Program ask me for some numbers a few times. I give list of numbers. I try to save them in List>. Numbers can be split by space. Now I have this code :

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TimeSeries {

public static void main(String[] args) {
// TODO Auto-generated method stub

System.out.println("Numbers of rows:");
Scanner in = new Scanner(System.in);
int NumberLines = in.nextInt();
in.nextLine();
String Ciag;
List<List<Integer>> ll = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < NumberLines; i++) {
list.clear();
Ciag = in.nextLine();
for (int t=0; t<Ciag.length(); t++) {

if(Character.isWhitespace(Ciag.charAt(t)))
{

}
else
}

}

System.out.println(list);
}

System.out.println(ll);

}

}

But my output is (example) :

Numbers of rows:
3
0 0 0
[0, 0, 0]
1 2 3
[1, 2, 3]
54 6 8
[5, 4, 6, 8]
[[5, 4, 6, 8], [5, 4, 6, 8], [5, 4, 6, 8]]

But I need to have [[0,0, 0], [1, 2, 3], [5, 4, 6, 8]]

The problem is that you add the same list into ll multiple times. You need to add different lists to get the behavior you want. For that, you need to create a fresh new list in each iteration of the for loop, instead of clearing and reusing the existing list.

Change these lines:

List<List<Integer>> ll = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < NumberLines; i++) {
list.clear();

To this:

List<List<Integer>> ll = new ArrayList<>();
for (int i = 0; i < NumberLines; i++) {
List<Integer> list = new ArrayList<>();
Source (Stackoverflow)