Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

java - Initializing array with values - should I explicitly instance the class or not?

I often see arrays being initialized like this:

String[] array = new String[] { "foo", "bar", "baz" };

But reading the Language Basics - Arrays shows that the short syntax doesn't require explicitly instancing the constructor:

Alternatively, you can use the shortcut syntax to create and initialize an array:

 int[] anArray = { 
     100, 200, 300,
     400, 500, 600, 
     700, 800, 900, 1000
 };

So, assuming these two methods of initialization:

String[] array = new String[] { "foo", "bar", "baz" };
String[] array2 = { "foo", "bar", "baz" };

Is there any difference between these? Both seems to work the same, in that case should I assume that the second one implicitly calls the new String[] and the first one is just a more verbose way, or is there more to it behind the scenes?

Starting with Java so sorry if this is way too stupid of a question, but I couldn't find anything about this in the web.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The two methods are equivalent. Note, however, that the concise syntax can only be used in variable declarations. Outside variable declarations you have to use the verbose syntax:

    String[] array;
    array = new String[] { "foo", "bar", "baz" }; // OK

    String[] array2;
    array2 = { "foo", "bar", "baz" };             // ERROR

For further discussion, see this answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...