2

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}};
    }
}
2
  • Since an array is a type of Object, I don't see why it should be impossible to create an array with a string as its first object and its array as its second object. Is there any way to work around this problem? Commented Mar 26, 2013 at 18:18
  • Why can't you crate Classs based on this. you can have Array of Objects of classes Commented Mar 26, 2013 at 18:21

2 Answers 2

6

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}};
Sign up to request clarification or add additional context in comments.

1 Comment

This is because the first is an array initializer assigned to a variable of an array type. You can't use this inside that array as the compiler doesn't know that it should be an array in that place.
2

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 } };

2 Comments

It could also be an array of Objects - that would be valid as well, I think.
@AndersonGreen: Yes, it would be valid. Basically we can't tell what kind of array you want from your original code - which is the problem the compiler has too. I have to say it's pretty unusual to want an array like this in the first place... are you sure a more strongly-typed data structure wouldn't be better?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.