Cast List<Object[]> to Object[][] in Java

半腔热情 提交于 2019-12-06 06:31:09

问题


How to turn List of arrays into two dimensional array in Java?

//Prepare the list
List<Object[]> conf = new LinkedList<Object[]>();
conf.add(new Object[]{ "FOO", "BAR"});
conf.add(new Object[]{ "FOO", "BAR"});

I tried:

Object[][] array = (Object[][]) conf.toArray(new Object[0]);

But it fails at ClassCastException:

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

回答1:


You are missing a pair of square brackets:

    Object[][] array = conf.toArray(new Object[0][]);
                                                 ^^

Or, if you wish to save on one unnecessary memory allocation:

    Object[][] array = conf.toArray(new Object[conf.size()][]);

The cast to Object[][] is unnecessary once the argument to toArray() has the correct type.



来源:https://stackoverflow.com/questions/15919948/cast-listobject-to-object-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!