Java 此处不允许使用数组初始值设定项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41658497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array initializer is not allowed here
提问by Abdurakhmon
I am working on Android project and I am getting an error which I cannot understand:
我正在处理 Android 项目,但遇到一个我无法理解的错误:
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?
这里发生了什么?
采纳答案by Jayanth
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.
您只能int[] pos = {0,1,2};
在变量初始化时使用缩写语法。
private int[] values1 = new int[]{1,2,3,4};
private int[] values2 = {1,2,3,4}; // short form is allowed only at variable initialization
回答by Robert Hume
Your initialization statement is wrong: you must add square bracketsto declare an array (and here you can omit the new
keyword because you're declaring and initializing the variable at the same time):
你的初始化语句是错误的:你必须添加方括号来声明一个数组(在这里你可以省略new
关键字,因为你同时声明和初始化变量):
int[] pos = { 0, 1, 2 };
In the onCreate
method, you can't omit the new
keywordbecause the variable was already declared, so you have to write:
在onCreate
方法中,不能省略new
关键字,因为变量已经声明了,所以必须写:
pos = new int[] { 2, 1, 0 };
You can read the Oracle documentationand the Java Language Specsfor more details.
回答by Sai Gopi N
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"};
回答by A. Abdullah
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:
这是一个编译时错误 Illegal Initializer for int。您可以通过在变量的数据类型后添加方括号来解决这个问题,如下所示:
int[] pos = {0, 1, 2};