Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 656
Mariusz Jamro Avatar asked Oct 15 '25 19:10

Mariusz Jamro


1 Answers

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.

like image 182
NPE Avatar answered Oct 18 '25 08:10

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!