Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initializer is not allowed here [duplicate]

Tags:

java

arrays

I am working on Android project and I am getting an error which I cannot understand:

Array initializer is not allowed here

I tried to simplify my code and it comes down to this

public class MainActivity extends Activity{      int pos = {0, 1, 2};      @Override     protected void onCreate(Bundle savedInstanceState){         super.onCreate(savedInstanceState);         setContentView(R.layout.main);         pos = {2, 1, 0};     } } 

What is going on here?

like image 724
Abdurakhmon Avatar asked Jan 15 '17 06:01

Abdurakhmon


People also ask

How do you initiate an array in Java?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

How do you fill an array in Kotlin?

In Kotlin There are Several Ways. Then simply initial value from users or from another collection or wherever you want. var arr = Array(size){0} // it will create an integer array var arr = Array<String>(size){"$it"} // this will create array with "0", "1", "2" and so on.


2 Answers

You should use

pos = new int[]{1,2,3}; 

You can only use the abbreviated syntax int[] pos = {0,1,2}; at variable initialization time.

private int[] values1 = new int[]{1,2,3,4}; private int[] values2 = {1,2,3,4}; // short form is allowed only at variable initialization 
like image 167
Jayanth Avatar answered Sep 19 '22 00:09

Jayanth


Your initialization statement is wrong: you must add square brackets to declare an array (and here you can omit the new keyword because you're declaring and initializing the variable at the same time):

int[] pos = { 0, 1, 2 }; 

In the onCreate method, you can't omit the new keyword because the variable was already declared, so you have to write:

pos = new int[] { 2, 1, 0 }; 

You can read the Oracle documentation and the Java Language Specs for more details.

like image 24
Robert Hume Avatar answered Sep 19 '22 00:09

Robert Hume