如何将ArrayList<String[]>转换为多维数组String[][]?

5

我有一个String[]值的集合,例如:

ArrayList<String[]> values = new ArrayList<>();

String[] data1 = new String[]{"asd", "asdds", "ds"};
String[] data2 = new String[]{"dss", "21ss", "pp"};

values.add(data1);
values.add(data2);

我需要将这个转换为多维数组String[][]。

当我尝试这样做:

String[][] arr = (String[][])values.toArray();

我遇到了一个ClassCastException的问题。

我该如何解决这个问题?

2个回答

7

这个有什么影响呢?(这个不需要 Java 11,而toArray(String[][]::new)则需要)

values.toArray(new String[0][0]);

那个方法是:

/**
 * Returns an array containing all of the elements in this list in proper
 * sequence (from first to last element); the runtime type of the returned
 * array is that of the specified array.  If the list fits in the
 * specified array, it is returned therein.  Otherwise, a new array is
 * allocated with the runtime type of the specified array and the size of
 * this list.

4

不需要转型,参考文档,你可以直接使用以下代码:

String[][] arr = values.toArray(new String[0][]);

Or if you are using Java 11

String[][] arr = values.toArray(String[][]::new);

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