Reputation: 84
i try to make a 2D arrayList when i accept data and store it into a single arraylist then added it to the 2d arraylist so i clear the single array list in every loop and save the new row the problem in clearing data it clear all bast row and just save the newest one enter code here
public class main6 {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(in);
int arrCol= scan.nextInt();
ArrayList<ArrayList<String>> arr = new ArrayList<ArrayList<String>>();
ArrayList<String> x = new ArrayList<String>();
for(int i = 0 ; i < arrCol ; i++) {
x.addAll(Arrays.asList(b.readLine().split("\\s")));
arr.add(i,x);
x.clear();
}
System.out.println(Arrays.deepToString(arr.toArray()));
}
}
Upvotes: 0
Views: 89
Reputation: 40057
A couple pf things.
List<List<String>> arr = new ArrayList<>();
for(int i = 0 ; i < arrCol ; i++) {
arr.add(Arrays.asList(b.readLine().split("\\s")));
}
ArrayList<>
implementation, then pass the output of Arrays.asList
as an argument. No need to use add or addAll. for(int i = 0 ; i < arrCol ; i++) {
arr.add(new ArrayList<>(Arrays.asList(b.readLine().split("\\s"))));
}
System.out.println(arr);
Note: One exception to to the first bullet. Sometimes, a List
implementation has more functionality in terms of methods
that are not in the List interface
. In that case, if you want that functionality, then you need to assign to the implementation type rather than the interface type. With List
interfaces, I cannot recall having to do that.
Upvotes: 1
Reputation: 148
Update the for loop to instantiate the array list:
for(int i = 0 ; i < arrCol ; i++) {
ArrayList<String> x = new ArrayList<>();
x.addAll(Arrays.asList(b.readLine().split("\\s")));
arr.add(i,x);
}
This way, the array list will be recreated for each loop and there is no need to clear it.
You can then remove the instantiation of the arraylist in the method body before the for-loop:
ArrayList<String> x = new ArrayList<String>();
Upvotes: 0
Reputation: 1147
Create the list in the for loop, so you have new instance for every addition:
for(int i = 0 ; i < arrCol ; i++) {
ArrayList<String> x = new ArrayList<String>();
...
... also, don't clear it afterwards...
Upvotes: 0