开发者

String array initialization as constructor parameter [duplicate]

This question already has answers here: Array initialization syntax wh开发者_运维技巧en not in a declaration (4 answers) Closed 7 years ago.

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

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:

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

But this works again:

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

Can someone explain why this is?


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

this is allowed at declaration time only

You can't

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


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


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

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜