44

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?

Ivar
  • 6,138
  • 12
  • 49
  • 61
Abdurakhmon
  • 2,813
  • 5
  • 20
  • 41

4 Answers4

96

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
Community
  • 1
  • 1
Jayanth
  • 5,954
  • 3
  • 21
  • 38
11

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.

Robert Hume
  • 1,129
  • 2
  • 14
  • 25
7

use the following syntax to declare/initialize and empty array, and then populated it with data:

String[] menuArray = {};
menuArray = new String[]{"new item","item 2"};
KirstieBallance
  • 1,238
  • 12
  • 26
saigopi.me
  • 14,011
  • 2
  • 83
  • 54
0

This is a compile-time error Illegal Initializer for int. You could solve this problem by adding square braces after your variable's data type like this:

int[] pos = {0, 1, 2};
thejufo
  • 133
  • 1
  • 7