数组参数声明导致调用发生的语法错误。然而,主要方法使用String []而不是String ...我如何理解这种不一致?为什么Java的主要方法使用String []而不是String dot dot dot
package domain.test;
import utilities.CConsole;
public class Tester {
public static void main(String[] args)
{
Test1 t = new Test1();
t.method1(0); // the array will exist but have a length of zero
t.method1(0, (Object[])null); // the array will not exist
t.method1(0, "a");
t.method1(0, "a", "b");
CConsole.pw.format("\n");
t.method2(0); // the array will exist but have a length of zero
t.method2(0, (String[])null); // the array will not exist
t.method2(0, "a");
t.method2(0, "a", "b");
CConsole.pw.format("\n");
}
}
class Test1 {
void method1(int number, Object... args) // Object[] causes syntax errors
{
if (args == null)
CConsole.pw.format("args == null\n");
else
{
CConsole.pw.format("args != null ");
CConsole.pw.format("args.length %d\n", args.length);
}
}
void method2(int number, String... args) // String[] causes syntax errors
{
if (args == null)
CConsole.pw.format("args == null\n");
else
{
CConsole.pw.format("args != null ");
CConsole.pw.format("args.length %d\n", args.length);
}
}
}
如何解释不一致性?
以下内容适用于表示编译的人员:要获取此错误更改method1()以使用Object []。
总结编辑:这一课似乎是这样的。正如@Andrew Barber强调的那样,String ...与String []不同。他们通常可以互换,所以不要试图以同样的方式对待他们(尽管我可以说出他们为什么看起来可以互换的原因)。他们是 main()的情况下可以互换。在main()
的情况下,有些人可能会称这种糖。
在函数参数中使用''''''是有效的,它不应该产生语法错误。它打印什么错误/ – birryree
不,只需复制代码并尝试。 – H2ONaCl
为什么它应该给出语法错误?使用String []作为参数没有什么问题 – ryanprayogo