简体   繁体   中英

difference in declaring your string array

Whats the difference between this :

String [] columns = new String []{KEY_ROWID, KEY_TITLE, KEY_DESC, KEY_TIME};

And This :

String [] columns={KEY_ROWID, KEY_TITLE, KEY_DESC, KEY_TIME};

None.

The latter version is a handy shortcut syntax that will only work in declaration statements, but the result is exactly the same.

They produce the same instantiation (only usable in declarations) of the string array, no difference at all in the result obtained. However, I mostly choose the first one (just a personal preference).

EDIT: Sorry, I was typing while the 1st answer appeared.

The first line uses an array creation expression that contains an array initializer, and the second line contains just the array initializer. Here, they perform the same exact function -- create and initialize an array. But only one is only valid when declaring the array.

The array initializer is defined in the JLS, Section 10.6 :

An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10)

 ArrayInitializer: { VariableInitializersopt ,opt } VariableInitializers: VariableInitializer VariableInitializers , VariableInitializer 

and Section 15.10 defines the array creation expression to require new SomeType[] :

An array creation expression is used to create new arrays (§10).

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

So, you can omit the new SomeType[] part if it's part of the declaration of the array variable, but you must include it elsewhere, such as an assignment expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM