[英]Convert ArrayList<Object[]> to Object[][]
How, in Java, do I convert an ArrayList of arrays to a two-dimensional array? 在Java中,我如何将数组的ArrayList转换为二维数组?
Example: 例:
ArrayList<String[]> results = new ArrayList<String[]>();
String [] columns = {a few strings};
JTable table = new JTable(results.toArray(), columns);
I get the error that JTable(Object[], Object[]) is not defined. 我得到了JTable(Object [],Object [])没有定义的错误。
The List<T>.toArray(T[])
method should do the job. List<T>.toArray(T[])
方法应该完成这项工作。
For example: 例如:
List<String[]> list = ...
String[][] res = new String[list.size()][];
list.toArray(res);
or 要么
List<String[]> list = ...
Object[][] res = new Object[list.size()][];
list.toArray(res);
If you use this overload rather than the List<T>.toArray()
overload, you can choose the actual type of the array. 如果使用此重载而不是List<T>.toArray()
重载,则可以选择数组的实际类型。 It takes one extra line of code, but if the array type is significant, this is the way to do it. 它需要一行额外的代码,但如果数组类型很重要,那就是这样做的方法。
(The List<T>.toArray()
overload gives you an array whose actual type is Object[]
... irrespective of the generic type of the list, or the actual type(s) of the list elements.) ( List<T>.toArray()
重载为您提供了一个数组,其实际类型为Object[]
..., 不管列表的泛型类型,还是列表元素的实际类型。)
在这种情况下, array.toArray()
将完成这一操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.