I have searched similar questions and I still cannot find the solution for my case. So basically, I have a 2D array called 'array2D' and I am trying to convert those into 2D arrayList. I tried to create an arrayList and used for loop to copy each of the elements from my array2D, which is a primitive 2D Array. I wonder if there is any clean and efficient way to do it.
Here is my code:
List<List<String>> arrayList2D = new ArrayList<List<String>>();
List<String> eachRecord = new ArrayList<String>();
for (int i=0; i< array2D.length; i++){
for(int j =0; j<array2D[1].length; j++){
eachRecord.add(String.valueOf(array2D[j]));
}
arrayList2D.add(eachRecord);
eachRecord.clear();
}
System.out.println(Arrays.toString(arrayList2D.toArray()));
The result returns empty arrayList, which means I failed to convert them.
[[], [], [], [], [], [], [], [], [], [], [], [], [], []]
I suspect the reason why I failed to populate the new ArrayList is because of the wrong usage of add method, I have tried push method as well and it was compile error. I wonder if there is any clean and efficient way to do it.