简体   繁体   English

用{{}}进行数组实例化

[英]array instantiation with `{…}`

Looking for verification on the following: 寻找以下方面的验证:

Is there any difference between the following two 以下两个之间有什么区别

int [] arr = new int[]{1, 2, 3}; 

int [] arr2 = {1, 2, 3}; 

?

To me - none. 对我来说-没有。 in effect anyways. 仍然有效。 {1, 2, 3} instantiates as well initializing it. {1, 2, 3}实例化并初始化它。 so-- no use at all invoking new ahead of it(?) 所以-根本没有必要在它之前调用new的东西(?)

TIA. TIA。

No, there's no difference in the examples you gave. 不,您提供的示例没有区别。 However, using new int[] allows you to separate the declaration and initialisation, as in: 但是,使用new int[]可以将声明和初始化分开,如:

int[] arr;
...
arr = new int[] { 1, 2, 3 };

whereas arr = {1, 2, 3}; arr = {1, 2, 3}; would not be allowed. 将不会被允许。

There's no difference at all in the two examples shown, they're equivalent. 所示的两个示例完全没有区别,它们是等效的。 But the first notation is needed, for instance if we have a method m() that receives as parameter, say, an int[] the only way to instantiate the array in-line would be: 但是第一个符号是必需的,例如,如果我们有一个方法m()接收参数,例如int[] ,则实例化内联数组的唯一方法是:

m(new int[]{1, 2, 3});

Because this won't work: 因为这行不通:

m({1, 2, 3});

Why is this? 为什么是这样? it was defined to be like that by the language designers, probably to avoid ambiguities when parsing the code. 语言设计者将其定义为类似语言,可能是为了避免在解析代码时产生歧义。

In the given example there is no differnce. 在给定的示例中,没有区别。

In general an array is either created by an array creation expression, eg using the new keyword ( §15.9 ) or an array initializer ( §10.6 ). 通常,数组是由数组创建表达式创建的,例如使用new关键字( §15.9 )或数组初始化器( §10.6 )。

An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. 数组创建表达式指定元素类型,嵌套数组的级别数以及至少一个嵌套级别的数组长度。 The array's length is available as a final instance variable length. 数组的长度可用作最终实例变量的长度。

An array initializer creates an array and provides initial values for all its components. 数组初始化器创建一个数组,并为其所有组件提供初始值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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