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);
    }   
}

Javadoc

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));

Try it on ideone

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.

Share:
11,537

Related videos on Youtube

Fili
Author by

Fili

Updated on May 31, 2022

Comments

  • Fili
    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

  • Fili
    Fili about 13 years
    With 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
    Nestor about 13 years
    Did you try the toArray(T []) ?
  • Harry Joy
    Harry Joy about 13 years
    @Gressie: +1, good suggestion. By this @Fili might be able to do it.
  • Fili
    Fili about 13 years
    It doesn't compile: "incompatible types; found: array MyObject[], required: array MyObject[][]"
  • Nestor
    Nestor about 13 years
    Actually, try it with a 0 by 0 matrix and it should still work ;)
  • Nestor
    Nestor about 13 years
    Clearer example of the solution
  • MarcoS
    MarcoS about 13 years
    you don't need to know the size of the matrix: see for example my code here
  • Fili
    Fili about 13 years
    I tried this solution even with some modification to the size of the matrix, but it doesn't compile :(
  • Jeremy
    Jeremy almost 13 years
    I knew I shouldn't have assumed modifying it real quick would break the compile. Fixed.
  • Fili
    Fili almost 13 years
    Thanks for the solution but it didn't compile. At end I solved with a loop.