Convert a list of array into an array of array
11,537
Solution 1
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);
}
}
Solution 2
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));
Solution 3
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.
Related videos on Youtube
Author by
Fili
Updated on May 31, 2022Comments
-
Fili almost 2 years
I have a list like this:
List<MyObject[]> list= new LinkedList<MyObject[]>();
and on Object like this:
MyObject[][] myMatrix;
How can I assign the "list" to "myMatrix"?
I don't want to loop over the list and assign element by element to MyMatrix, but I want to assign it directly (with the oppurtune modifications) if possible. Thanks
-
Lars about 13 yearsstackoverflow.com...fill-a-array-with-list-data is a nearly a duplicate
-
-
Fili about 13 yearsWith toArray() the editor says "incompatible types; found: array java.lang.Object[], required: array Item[][]". I tried to cast the result of toArray() but it give me a ClassCastException
-
Nestor about 13 yearsDid you try the toArray(T []) ?
-
Harry Joy about 13 years@Gressie: +1, good suggestion. By this @Fili might be able to do it.
-
Fili about 13 yearsIt doesn't compile: "incompatible types; found: array MyObject[], required: array MyObject[][]"
-
Nestor about 13 yearsActually, try it with a 0 by 0 matrix and it should still work ;)
-
Nestor about 13 yearsClearer example of the solution
-
MarcoS about 13 yearsyou don't need to know the size of the matrix: see for example my code here
-
Fili about 13 yearsI tried this solution even with some modification to the size of the matrix, but it doesn't compile :(
-
Jeremy almost 13 yearsI knew I shouldn't have assumed modifying it real quick would break the compile. Fixed.
-
Fili almost 13 yearsThanks for the solution but it didn't compile. At end I solved with a loop.