如何在 Java 中初始化数组? [英] How to initialize an array in Java?
问题描述
我正在像这样初始化一个数组:
I am initializing an array like this:
public class Array {
int data[] = new int[10];
/** Creates a new instance of Array */
public Array() {
data[10] = {10,20,30,40,50,60,71,80,90,91};
}
}
NetBeans 指出这一行的错误:
NetBeans points to an error at this line:
data[10] = {10,20,30,40,50,60,71,80,90,91};
我该如何解决问题?
推荐答案
data[10] = {10,20,30,40,50,60,71,80,90,91};
以上不正确(语法错误).这意味着您要为 data[10]
分配一个数组,该数组只能容纳一个元素.
The above is not correct (syntax error). It means you are assigning an array to data[10]
which can hold just an element.
如果要初始化数组,请尝试使用 数组初始化器:
If you want to initialize an array, try using Array Initializer:
int[] data = {10,20,30,40,50,60,71,80,90,91};
// or
int[] data;
data = new int[] {10,20,30,40,50,60,71,80,90,91};
注意两个声明之间的区别.将新数组分配给声明的变量时,必须使用 new
.
Notice the difference between the two declarations. When assigning a new array to a declared variable, new
must be used.
即使你更正了语法,访问data[10]
仍然是错误的(你只能访问data[0]
到data[9]
因为 Java 中数组的索引是从 0 开始的).访问 data[10]
将抛出一个 ArrayIndexOutOfBoundsException.
Even if you correct the syntax, accessing data[10]
is still incorrect (You can only access data[0]
to data[9]
because index of arrays in Java is 0-based). Accessing data[10]
will throw an ArrayIndexOutOfBoundsException.
这篇关于如何在 Java 中初始化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!