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

后端 未结 2 1568
礼貌的吻别
礼貌的吻别 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:35

    The sane way of declaring a variable is

    type name
    

    So if type is int[], we should write

    int[] array
    

    Never write

    int array[]
    

    it is gibberish (though it's legal)

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

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