将一个数组列表转换为一个二维数组

19

我有一个列表像这样:

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

就像这样的对象:

MyObject[][] myMatrix;

我该如何将“list”分配给“myMatrix”?

我不想逐个循环遍历列表并将其赋值给MyMatrix,而是希望在可能的情况下直接进行分配(并进行必要的修改)。 谢谢。


stackoverflow.com...fill-a-array-with-list-data 几乎是一个重复的问题。 - Lars
6个回答

22
您可以使用 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

(这是HTML代码,无需翻译)

无法编译:“不兼容的类型;找到:数组MyObject [],需要:数组MyObject [][]” - Fili
1
实际上,你可以尝试使用一个0乘0的矩阵,它仍然能够正常工作 ;) - Gressie
你不需要知道矩阵的大小:例如,可以查看我的代码这里 - MarcoS
我尝试了这个解决方案,甚至对矩阵的大小进行了一些修改,但它无法编译 :( - Fili
我知道我不应该假设快速修改它会破坏编译。已修复。 - Jeremy
1
谢谢提供的方案,但是它没有编译通过。 最终我用循环解决了问题。 - Fili

9
以下代码片段展示了一个解决方案:
// 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


解决方案的更清晰示例 - Gressie

1
让我们假设我们有一个'int'数组列表。
List<int[]> list = new ArrayList();

现在,为了将它转换成类型为“int”的2D数组,我们使用“toArray()”方法。
int result[][] = list.toArray(new int[list.size()][]);

我们可以进一步概括它,例如 -
List<T[]> list = new ArrayList();
T result[][] = list.toArray(new T[list.size()][]);

这里,T是数组的类型。

0
你可以这样做:
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 + "]";
    }

}

0

使用toArray()时,编辑器会提示“不兼容的类型;找到:数组java.lang.Object[],需要:数组Item[][]”。 我尝试对toArray()的结果进行强制转换,但它给了我一个ClassCastException。 - Fili
2
你尝试过使用 toArray(T []) 吗? - Gressie
@Gressie: +1,好建议。这样@Fili或许能做到。 - Harry Joy

0

使用 List.Array() 将列表转换为数组。

然后使用 System.arraycopy 将其复制到二维数组中,这对我很有效。

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接