英文:
why I need 'new' for array parameter?
问题
int add(int[] scores){ ... }
int result = add(new int[] {1,2,3}); //correct
我知道我必须这样编码,但为什么我们必须在参数中使用 'new int[]'?
英文:
int add(int[] scores){ ... }
-------------------------------
int result = add({1,2,3}); //wrong
int result = add(new int[] {1,2,3}); //correct
I know I have to code like this but
why we must put 'new int[]' for parameter??
答案1
得分: 3
数组初始化语法({1, 2, 3}
)只能在特定情况下使用:
> 数组初始化器可以在字段声明(§8.3,§9.3)或局部变量声明(§14.4)中指定,或作为数组创建表达式(§15.10.1)的一部分,用于创建数组并提供一些初始值。
在其他情况下,您需要使用数组创建表达式(例如 new int[] {1, 2, 3}
)。
这只是语言规范的规定。可能会有所不同,但实际情况并非如此。
英文:
The array initializer syntax ({1, 2, 3}
) can only be used in certain circumstances:
> An array initializer may be specified in a field declaration (§8.3, §9.3) or local variable declaration (§14.4), or as part of an array creation expression (§15.10.1), to create an array and provide some initial values.
In other circumstances, you would need to use an array creation expression (e.g. new int[] {1, 2, 3}
).
This is just how the language is specified. It could be different, but it's not.
答案2
得分: 0
如已指出,数组初始化只能用于变量声明。
你可能希望在你的示例中使用可变参数,就像这样:
int add(int... scores){ ... }
你可以以两种方式调用它:
int result = add(1,2,3);
int result = add(new int[] {1,2,3});
英文:
As it has been pointed out, the array initialize can only be used in variable declarations.
You might want to use varargs in you example like that:
int add(int... scores){ ... }
You can call it in two ways:
int result = add(1,2,3);
int result = add(new int[] {1,2,3});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论