Array initializer is not allowed here

Array initializer is not allowed here

The use of array is divided into declaration and initialization, which can be carried out simultaneously or separately

Int [] array; declaration

Array = New Int {element1, Element2, element3..}; initialization mode 1

Array = New Int [length]; initialization mode 2

There are two initialization methods for arrays

1、 Static initialization: the initial value of each array element is explicitly specified by the programmer during initialization;

    arrayName = new type[]{element1,element2,element3…}

2、 Dynamic initialization: when initializing, the programmer specifies the length of the array, and the system initializes the default value of each array element.

    arrayName = new type[length];

Note: do not use static initialization and dynamic initialization at the same time. In other words, do not specify the length of the array and divide each element of the array

The initial value is set.
 

Looking at the code today, we can see a simplified array initialization method, which belongs to the simplified version of static initialization, but there is something wrong with it

Int [] array = {1,2,3}; object [] obj = {}; this is OK

So I tried to write like this

Class member variables declare an array int [] elementdata, but it is not initialized;

Initialize it in the constructor, trying to write like this

Elementdata = {1,3,5}, so the above compilation error prompt appears

It seems that this simplified way of writing is not applicable here,

The use of arrays must be initialized

Suppose that elementdata = {1,3,5} does not generate new objects through new. Maybe the compiler thinks that it has been declared but not initialized

Therefore, it is recommended that the initialization is completed when the array is declared

Int [] elementdata = {1,3,5}; this is OK, declaration and assignment are done at the same time

Read More: