Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 891
user3435580 Avatar asked Mar 21 '14 08:03

user3435580


People also ask

Can you have a mixed data type array in Java?

Yes we can store different/mixed types in a single array by using following two methods: Method 1: using Object array because all types in .

How do you create a mixed array?

You can create JavaScript array with mixed data types as well, for example, array containing both numbers and strings: var MixArr = [1, “Mixed”, 2, “Array”]; You may also use new keyword to create array objects: var JSArr = new array (1,2,3,”String”);

Can array have different data types?

You can create an array with elements of different data types when declare the array as Object. Since System. Object is the base class of all other types, an item in an array of Objects can have a reference to any other type of object.

How do you declare an array which can hold any type of objects?

An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.


1 Answers

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} };
like image 135
sybear Avatar answered Sep 20 '22 00:09

sybear