Why int[] a = new int[1] instead of just int a?

后端 未结 6 1473
无人及你
无人及你 2021-02-09 11:55

Is there some hidden meaning in this code which I don\'t see in java? How can it be useful?

int[] a = new int[1];

than just

int         


        
6条回答
  •  情歌与酒
    2021-02-09 12:32

    int a;
    

    defines a variable that can hold an int

    int[] a;
    

    defines a variable that can hold an array of int

    int[] a = new int[1];
    

    does that above but also initializes it by actually creating an array (of size 1 - it can hold 1 int) and defines the variable a to hold that array, but doesn't define what's in the array.

    int[] a = new int[1]{1};
    

    does that above but also defines what's in the array: the int 1.

    I suppose it does a similar thing, in that space is allocated for 1 int, but the array also defines an array. I suppose you could say these are similar:

    int a = 1;
    int b = a + 1;
    // now b == 2
    
    int[] a = new int[1]{1};
    int b = a[0] + 1;   
    // now b == 2
    

提交回复
热议问题