Search code examples
javaarrayscharsequence

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


Is there any difference between those to initializations of array?

CharSequence colors[] = new CharSequence[] {"red", "green", "blue", "black"};
CharSequence colors[] = {"red", "green", "blue", "black"};

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