如何在 Java 中初始化一个数组?

2022-01-18 00:00:00 arrays initialization 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};

我该如何解决这个问题?

How can I solve the problem?

推荐答案

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.

相关文章