用值初始化数组-我应该显式地实例化该类吗? [英] Initializing array with values - should I explicitly instance the class or not?

查看:41
本文介绍了用值初始化数组-我应该显式地实例化该类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到这样初始化数组:

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

这些之间有什么区别吗?两者似乎都一样,在这种情况下,我应该假设第二个隐式调用 new String [] ,第一个只是更冗长的方式,或者后面还有更多内容场景?

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?

从Java开始,如果这个问题太愚蠢了,抱歉,但是我在网络上找不到任何有关此的信息.

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.

推荐答案

这两个方法是等效的.但是请注意,简洁的语法只能在变量声明中使用.在变量声明之外,您必须使用详细语法:

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.

这篇关于用值初始化数组-我应该显式地实例化该类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆