How to initialize an array in Java?

后端 未结 10 2075
天命终不由人
天命终不由人 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:11

    You cannot initialize an array like that. In addition to what others have suggested, you can do :

    data[0] = 10;
    data[1] = 20;
    ...
    data[9] = 91;
    
    0 讨论(0)
  • 2020-11-22 01:17

    Syntax

     Datatype[] variable = new Datatype[] { value1,value2.... }
    
     Datatype variable[]  = new Datatype[] { value1,value2.... }
    

    Example :

    int [] points = new int[]{ 1,2,3,4 };
    
    0 讨论(0)
  • 2020-11-22 01:23

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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题