Convert a list of array into an array of array
The following snippet shows a solution:
// create a linked list
List<String[]> arrays = new LinkedList<String[]>();
// add some trivial test data (note: arrays with different lengths)
arrays.add(new String[]{"a", "b", "c"});
arrays.add(new String[]{"d", "e", "f", "g"});
// convert the datastructure to a 2D array
String[][] matrix = arrays.toArray(new String[0][]);
// test output of the 2D array
for (String[] s:matrix)
System.out.println(Arrays.toString(s));
Try it on ideone
You could use toArray(T[])
.
import java.util.*;
public class Test{
public static void main(String[] a){
List<String[]> list=new ArrayList<String[]>();
String[][] matrix=new String[list.size()][];
matrix=list.toArray(matrix);
}
}
Javadoc
Let us assume that we have a list of 'int' array.
List<int[]> list = new ArrayList();
Now to convert it into 2D array of type 'int', we use 'toArray()' method.
int result[][] = list.toArray(new int[list.size()][]);
We can generalize it further like-
List<T[]> list = new ArrayList();
T result[][] = list.toArray(new T[list.size()][]);
Here, T is the type of array.