为什么我需要为数组参数使用 ‘new’?

huangapple go评论77阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年9月3日 18:08:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63721393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定