Anderson Green
Anderson Green

Reputation: 31850

Java multidimensional array initializers

Here, I'm trying to initialize an array of Objects in Java, but I can't figure out how to initialize a nested array of objects. I tried creating an array of objects with a string as the first element and an array of strings as the second element.

The error message that I encountered:

Main.java:8: error: illegal initializer for Object

And the code that produced this error was:

import java.util.*;
import java.lang.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Object[] multiDimensionalObjectArray = {"Hi!", {5, 5}};
    }
}

Upvotes: 2

Views: 2247

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503379

You're not creating a multi-dimensional array. You're creating an array where the first element is a string - that's not an array to start with. Sure, you can make the second element an array... what kind of array do you want it to be? Given that it contains two integers, maybe you want it to be an int[]:

Object[] mixedDataArray = { "Hi!", new int[] { 5, 5 } };

Upvotes: 2

rgettman
rgettman

Reputation: 178333

For some reason, even if you don't need a new Object[] in front of the main array literal, it appears that you need one for the inner array literal:

Object[] multiDimensionalObjectArray = {"Hi!", new Object[] {5, 5}};

Upvotes: 6

Related Questions