Mixed type and mixed array type array Object[] in java not compiling

user3435580 picture user3435580 · Mar 21, 2014 · Viewed 13.9k times · Source

Here is how it looks like

public Object[] settings = {true, true, false, 1, true, false, 10, 10, 20, false, false, false, false, false, {true, true, true, true}};

Error:

 illegal initializer for java.lang.Object

In another IDE I get this error.

Static Error: Array initializer must be assigned to an array type

Answer

vikingmaster picture vikingmaster · Mar 21, 2014

Initialize Array like this:

public Object[] settings = new Object[]{true, true, false, 1};

However, you cannot have arrays and values in the same dimension, because every element in a dimension must of the same type. (Strictly array '{}' OR Object in our case)

new Object[]{true, true, false, 1, {true, false} }; //<--- Illegal initializer

Instead just use several dimensions and group values in arrays:

public Object[][] settings = new Object[][]{{true, true}, {false, 1, 3}};

Either use ArrayList or LinkedList where it is possible to create any array you like.


Update

In fact it is possible to mix elements like this:

new Object[]{true, false, 1, new Object[]{true, false} };