我有一个列表像这样:
List<MyObject[]> list= new LinkedList<MyObject[]>();
就像这样的对象:
MyObject[][] myMatrix;
我该如何将“list”分配给“myMatrix”?
我不想逐个循环遍历列表并将其赋值给MyMatrix,而是希望在可能的情况下直接进行分配(并进行必要的修改)。 谢谢。
我有一个列表像这样:
List<MyObject[]> list= new LinkedList<MyObject[]>();
就像这样的对象:
MyObject[][] myMatrix;
我该如何将“list”分配给“myMatrix”?
我不想逐个循环遍历列表并将其赋值给MyMatrix,而是希望在可能的情况下直接进行分配(并进行必要的修改)。 谢谢。
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);
}
}
(这是HTML代码,无需翻译)// 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));
List<int[]> list = new ArrayList();
int result[][] = list.toArray(new int[list.size()][]);
List<T[]> list = new ArrayList();
T result[][] = list.toArray(new T[list.size()][]);
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]));
}
输出为
[Item [name=foo], Item [name=bar]]
[Item [name=f], Item [name=o], Item [name=o]]
假设Item如下:
public class Item {
private String name;
public Item(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "Item [name=" + name + "]";
}
}
使用 List.Array()
将列表转换为数组。
然后使用 System.arraycopy
将其复制到二维数组中,这对我很有效。
Object[][] destination = new Object[source.size()][];
System.arraycopy(source, 0, destination, 0, source.size());