How is this illegal

2020-02-07 08:01发布

问题:

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 are giving size in initialization . Then how is statement (a) illegal and statement (b) is legal in java

回答1:

int i1[] = new int[]{1,2};
int[][] i2 = new int[][]{{1,2,3},{4,5,6}}; 


回答2:

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


回答3:

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


回答4:

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}};
                     ^       ^        ^


回答5:

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};



标签: java arrays