Kamila 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();
System.out.println("Add row " +(i+1));
Ciag = in.nextLine();
for (int t=0; t<Ciag.length(); t++) {

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

}
else
{list.add(Character.getNumericValue(Ciag.charAt(t)));
}

}

System.out.println(list);
ll.add(list);
}

System.out.println(ll);

}


}


But my output is (example) :

Numbers of rows:
3
Add row 1
0 0 0
[0, 0, 0]
Add row 2
1 2 3
[1, 2, 3]
Add row 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]]

Answer

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<>();
Comments