繁体   English   中英

如何转换 ArrayList<string[]> 到多维数组 String[][]?</string[]>

[英]How to convert ArrayList<String[]> to multidimensional array String[][]?

我有一个 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

我怎么解决这个问题?

这个怎么样(这不需要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.

不需要,检查文档,你可以使用:

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

或者,如果您使用的是Java 11

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM