Java: convert array list to array array

I have a list like this:

List<MyObject[]> list= new LinkedList<MyObject[]>(); 

and on an object like this:

 MyObject[][] myMatrix; 

How to assign the "list" to "myMatrix"?

I donโ€™t want to iterate over the list and assign an element by MyMatrix element, but if possible, I want to assign it directly (with opportunistic modifications). Thanks

+4
source share
4 answers

You can 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

+7
source

The following snippet shows the 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 on ideon

+3
source

Use the toArray () or toArray (T []) of the LinkedList method.

0
source

You can do it as follows:

 public static void main(String[] args) { List<Item[]> itemLists = new ArrayList<Item[]>(); itemLists.add(new Item[] {new Item("foo"), new Item("bar")}); itemLists.add(new Item[] {new Item("f"), new Item("o"), new Item("o")}); Item[][] itemMatrix = itemLists.toArray(new Item[0][0]); for (int i = 0; i < itemMatrix.length; i++) System.out.println(Arrays.toString(itemMatrix[i])); } 

Output

 [Item [name=foo], Item [name=bar]] [Item [name=f], Item [name=o], Item [name=o]] 

assuming Item is as follows:

 public class Item { private String name; public Item(String name) { super(); this.name = name; } @Override public String toString() { return "Item [name=" + name + "]"; } } 
0
source

All Articles