Array declaration and initialization in Java. Arrays behave differently, when the position of their subscript indices is changed in their declaration

后端 未结 2 1594
礼貌的吻别
礼貌的吻别 2021-01-01 09:25

The following is the obvious and usual array declaration and initialization in Java.

int r[], s[];       //<-------
r=new int[10];
s=new int[10];
<         


        
2条回答
  •  清酒与你
    2021-01-01 09:37

    Look at JLS on Arrays:

    The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

    and

    Brackets are allowed in declarators as a nod to the tradition of C and C++. The general rules for variable declaration, however, permit brackets to appear on both the type and in declarators, so that the local variable declaration:

    float[][] f[][], g[][][], h[];  // Yechh!
    

    is equivalent to the series of declarations:

    float[][][][] f;
    float[][][][][] g;
    float[][][] h;
    

    So for example:

    int []p, q[];
    

    is just

    int[] p, q[]
    

    which is in fact

    int p[]; int q[][]
    

    The rest are all similar.

提交回复
热议问题