java为什么我不能使用{“a”,“b”}作为字符串数组方法参数的输入
我想知道,为什么我不能使用{“a”,“b”}作为字符串数组方法参数的输入
public static void fun(String[] s) {
}
public static void main(String[] args) {
String[] s = {"a", "b"};
// OK
fun(s);
// This line is not accepted by compiler
fun({"a", "b"});
}
# 1 楼答案
从section 10.3 of the JLS:
数组初始值设定项语法仅在变量声明的一部分中直接有效。在其他任何地方(包括以后的赋值),都必须使用数组创建表达式:
我怀疑这基本上使语言在如何指定方面变得更简单
# 2 楼答案
你应该使用:
在java中,甚至字符串数组也被视为对象。您需要字符串数组的对象作为
fun
参数。这个对象由String[]{"a","b"}
提供,它是一个anonymous String array
完全构造和初始化的对象