How to initialize an array in Java?

后端 未结 10 2212
天命终不由人
天命终不由人 2020-11-22 00:23

I am initializing an array like this:

public class Array {

    int data[] = new int[10]; 
    /** Creates a new instance of Array */
    public Array() {
           


        
10条回答
  •  独厮守ぢ
    2020-11-22 01:23

    If you want to initialize an array in a constructor, you can't use those array initializer like.

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

    Just change it to

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

    You don't have to specify the size with data[10] = new int[] { 10,...,91} Just declare the property / field with int[] data; and initialize it like above. The corrected version of your code would look like the following:

    public class Array {
    
        int[] data;
    
        public Array() {
            data = new int[] {10,20,30,40,50,60,71,80,90,91};
        }
    
    }
    

    As you see the bracket are empty. There isn't any need to tell the size between the brackets, because the initialization and its size are specified by the count of the elements between the curly brackets.

提交回复
热议问题