以下代码在Java中使用简单的String数组。在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" });
但编译器抱怨“表达式非法启动不是语句”为什么?
我猜你会莫名其妙地需要通过字符串数组的参考。通过你在做什么,那不会发生。 – noMAD 2012-04-12 03:47:57
如果编译器看到“{1,12,57}”,它应该是什么,“byte []”,“short []”,“short”,“ int []',还是'long []'?用明确的类型,歧义消失了。 – trutheality 2012-04-12 03:59:32