问题描述
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.
,
不需要不需要投射,勾选the doc,你可以直接使用:
String[][] arr = values.toArray(new String[0][]);
或者如果您使用的是 Java 11
String[][] arr = values.toArray(String[][]::new);