Is there any difference initializing array by enumaration XOR new type[] + enumaration?

StackOverflow https://stackoverflow.com/questions/22852499

  •  27-06-2023
  •  | 
  •  

Question

Is there any difference between those to initializations of array?

CharSequence colors[] = new CharSequence[] {"red", "green", "blue", "black"};
CharSequence colors[] = {"red", "green", "blue", "black"};
Était-ce utile?

La solution

No, there are not. They will be compiled into the same byte code.

For reference, the Java Language Specification states

An array is created by an array creation expression (§15.10) or an array initializer (§10.6).

where array creation expression, ie. the new CharSequence[] part, is defined as

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 [ ]

and array initializer, ie. the {...} part, is defined as

ArrayInitializer:
    { VariableInitializersopt ,opt }

VariableInitializers:
    VariableInitializer
    VariableInitializers , VariableInitializer  

VariableInitializer:
    Expression
    ArrayInitializer
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top