Do I have to loop through each element to convert ArrayList<String[]> to String[][] or is there a more efficient way?
2 Answers
Just get the contents as an array
List<String[]> list = new ArrayList<>();
...
String[][] array = list.toArray(new String[0][0]); // the size here is not important, the array is just an indication of the type to use
1 Comment
Radiodef
It's better to specify the correct size as in
list.toArray(new String[list.size()][]), otherwise a new array is instantiated with reflection.You can use .toArray(T[]) for this.
public static void main(String[] args) {
List<String[]> l = new ArrayList<String[]>();
String[] a = {"lala", "lolo"};
String[] b = {"lili", "lulu"};
l.add(a);
l.add(b);
String[][] r = new String[l.size()][];
r = l.toArray(r);
for(String[] s : r){
System.out.println(Arrays.toString(s));
}
}
Output:
[lala, lolo]
[lili, lulu]