How is this illegal

前端 未结 5 1487
南方客
南方客 2020-12-12 06:12
a) int i[] = new int[2]{1,2};
b) int[] i = new int[]{1,2,3}{4,5,6}; 

I know we cannot give size of an array at declaration . But in statement(a) we

相关标签:
5条回答
  • 2020-12-12 06:13

    Why not consult the Java Language Specification?

    JLS 15.10 - Array Creation Expressions

    ArrayCreationExpression:
    new PrimitiveType DimExprs Dimsopt
    new ClassOrInterfaceType DimExprs Dimsopt
    new PrimitiveType Dims ArrayInitializer
    new ClassOrInterfaceType Dims ArrayInitializer
    
    DimExprs:
    DimExpr
    DimExprs DimExpr
    
    DimExpr:
    [ Expression ]
    
    Dims:
    [ ]
    Dims [ ]
    

    Notice that this means that array creation expressions with initializers can only have empty brackets.

    Array initializers are defined in 10.6

    ArrayInitializer:
    { VariableInitializersopt ,opt }
    
    VariableInitializers:
    VariableInitializer
    VariableInitializers , VariableInitializer
    
    The following is repeated from §8.3 to make the presentation here clearer:
    VariableInitializer:
    Expression
    ArrayInitializer
    
    0 讨论(0)
  • 2020-12-12 06:13

    a) Cannot define dimension expressions when an array initializer is provided int i[] = new int[2]; b) Syntax error on token(s), misplaced construct(s) int[] j = new int[]{1,2,3};

    0 讨论(0)
  • 2020-12-12 06:27
    int i1 [] = new int [2] {1, 2}; // Invalid
    int i2 [] = new int [] {1, 2}; // Valid
    int [] i3 = new int [][] {1, 2, 3} {4, 5, 6}; // Invalid
    int [][] i4 = new int [][] {new int [] {1, 2, 3}, new int [] {4, 5, 6}}; // Valid
    
    0 讨论(0)
  • 2020-12-12 06:37
    int i1[] = new int[]{1,2};
    int[][] i2 = new int[][]{{1,2,3},{4,5,6}}; 
    
    0 讨论(0)
  • 2020-12-12 06:39

    Both are illegal!

    a) You either specify the size or the content. Legal would be:

    int i[] = new int[2];
    i[0] = 1;
    i[1] = 2;
    

    or

    int i[] = new int[]{1,2};
    

    b) 2-dimensional arrays are arrays containing arrays. So, you have to write:

    int[] i = new int[][]{{1,2,3}, {4,5,6}};
                         ^       ^        ^
    
    0 讨论(0)
提交回复
热议问题