Java 字符串数组初始化作为构造函数参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4436458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:28:57  来源:igfitidea点击:

String array initialization as constructor parameter

javaarraysstringconstructor

提问by Hermann Hans

In Java, it is completely legal to initialize a String array in the following way:

在 Java 中,通过以下方式初始化 String 数组是完全合法的:

String[] s = {"FOO", "BAR"};

However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed:

但是,当尝试实例化一个将 String 数组作为参数的类时,不允许使用以下代码:

Test t = new Test({"test"});

But this works again:

但这又奏效了:

Test t = new Test(new String[] {"test"});

Can someone explain why this is?

有人可以解释为什么会这样吗?

采纳答案by Jigar Joshi

String[] s = {"FOO", "BAR"};  

this is allowed at declaration time only

这仅在声明时允许

You can't

你不能

String[] s;
s={"FOO", "BAR"};  

回答by Karl Knechtel

Because Type[] x = { ... }is an initializationsyntax for arrays. The { ... }is interpreted in a specific way only in that specific context.

因为Type[] x = { ... }是数组的初始化语法。将{ ... }仅在特定语境解释以特定的方式。

回答by Peter Lawrey

For you want a simple way to pass a String array, I suggest you use varargs

如果你想要一个简单的方法来传递一个 String 数组,我建议你使用 varargs

class Test {
   public Test(String...args);
}

// same as new Test(new String[] { "test", "one" })
Test t = new Test("test", "one");