开发者

Convert a list of array into an array of array

开发者 https://www.devze.com 2023-03-01 04:36 出处:网络
I have a list like this: List<MyObject[]> list= new LinkedList&开发者_如何学Golt;MyObject[]>();

I have a list like this:

List<MyObject[]> list= new LinkedList&开发者_如何学Golt;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


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


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


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.


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


You can do it like this:

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 is

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

assuming that 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 + "]";
    }

}


Converto list to array using. List.Array()

Then Use System.arraycopy to copy to the 2d array works well for me

Object[][] destination = new Object[source.size()][];

System.arraycopy(source, 0, destination, 0, source.size());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号