简体   繁体   English

将arrayList <Object []>转换为嵌套数组

[英]convert an arrayList<Object[]> into a nested array

This is the following idea: 这是以下想法:

List<Object[]> ret = new ArrayList<>();
ret.add(new Object[]{"a", 1});
Object[][] obj = (Object[][]) ret.toArray();

but it doesn't work: toArray returns Object[] 但它不起作用: toArray返回Object []

Caused by: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Object;

Any idea? 任何的想法?

There is a version of toArray that accepts an array as an argument. 有一个版本的toArray接受一个数组作为参数。 This allows you to specify what type of array you want returned. 这允许您指定要返回的数组类型。

Object[][] obj = ret.toArray(new Object[0][]);

You can pass in an array big enough to hold the contents of your list; 您可以传入足够大的数组来保存列表中的内容; or you can pass in an array of zero size and the list implementation should return a new array of the same type as the one you passed in. 或者你可以传入一个零大小的数组,列表实现应该返回一个与你传入的数组相同类型的新数组。

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

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