Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

java - 如何在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 points to an error at this line:

(NetBeans在此行指出一个错误:)

data[10] = {10,20,30,40,50,60,71,80,90,91};

How can I solve the problem?

(我该如何解决这个问题?)

  ask by chatty translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
data[10] = {10,20,30,40,50,60,71,80,90,91};

The above is not correct (syntax error).

(上面的信息不正确(语法错误)。)

It means you are assigning an array to data[10] which can hold just an element.

(这意味着您正在为只能分配一个元素的data[10]分配一个数组。)

If you want to initialize an array, try using Array Initializer :

(如果要初始化数组,请尝试使用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};

Notice the difference between the two declarations.

(注意两个声明之间的区别。)

When assigning a new array to a declared variable, new must be used.

(将新数组分配给已声明的变量时,必须使用new 。)

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).

(即使您纠正了语法,访问data[10]仍然是错误的(您只能访问data[0]data[9]因为Java中数组的索引是基于0的)。)

Accessing data[10] will throw an ArrayIndexOutOfBoundsException .

(访问data[10]将抛出ArrayIndexOutOfBoundsException 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...