gpt4 book ai didi

java - 在 Java 中将数组作为方法参数传递

转载 作者:搜寻专家 更新时间:2023-10-31 19:40:52 24 4
gpt4 key购买 nike

以下代码使用 Java 中的简单字符串数组。

package javaarray;

final public class Main
{
public void someMethod(String[] str)
{
System.out.println(str[0]+"\t"+str[1]);
}
public static void main(String[] args)
{
String[] str1 = new String[] {"day", "night"};
String[] str2 = {"black", "white"};

//Both of the above statements are valid.

Main main=new Main();
main.someMethod(str1);
main.someMethod(str2);

//We can invoke the method someMethod by supplying both of the above arrays alternatively.

main.someMethod(new String[] { "day", "night" }); //This is also valid as obvious.
main.someMethod({ "black", "white" }); //This is however wrong. The compiler complains "Illegal start of expression not a statement" Why?
}
}

在上面的代码片段中,我们可以像这样初始化数组。

String[] str1 = new String[] {"day", "night"};
String[] str2 = {"black", "white"};

我们可以直接将它传递给一个方法,而无需像这样分配。

main.someMethod(new String[] { "day", "night" });

如果是这样,那么下面的说法也应该有效。

main.someMethod({ "black", "white" });

但是编译器提示“表达式的非法开始不是语句”为什么?

最佳答案

根据 Java 语言规范 (10.6. Array Initializers)

An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values:

因此,只有两种方法可以使用数组初始值设定项 ({"foo", "bar"}):

  1. 变量声明:String[] foo = {"foo", "bar"};
  2. 数组创建表达式:new String[] {"foo", "bar"};

您不能将数组初始值设定项用作方法参数。

15.10. Array Creation Expressions

ArrayCreationExpression:    new PrimitiveType DimExprs Dimsopt    new ClassOrInterfaceType DimExprs Dimsopt    new PrimitiveType Dims ArrayInitializer     new ClassOrInterfaceType Dims ArrayInitializer

关于java - 在 Java 中将数组作为方法参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10117077/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com