2012-04-12 125 views
5

以下代碼在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" }); 

但編譯器抱怨「表達式非法啓動不是語句」爲什麼?

+0

我猜你會莫名其妙地需要通過字符串數組的參考。通過你在做什麼,那不會發生。 – noMAD 2012-04-12 03:47:57

+1

如果編譯器看到「{1,12,57}」,它應該是什麼,「byte []」,「short []」,「short」,「 int []',還是'long []'?用明確的類型,歧義消失了。 – trutheality 2012-04-12 03:59:32

回答

8

根據Java語言規範(10.6. Array Initializers

數組初始化可在聲明中指定,或作爲陣列創建表達式(§15.10)的一部分,形成一個陣列,並提供一些初始值:

所以,只有兩種方法可以使用數組初始化({"foo", "bar"}):

  1. 變量聲明:String[] foo = {"foo", "bar"};
  2. 數組創建表達式:new String[] {"foo", "bar"};

不能使用數組初始化作爲方法參數。

15.10. Array Creation Expressions

 
ArrayCreationExpression: 
    new PrimitiveType DimExprs Dimsopt 
    new ClassOrInterfaceType DimExprs Dimsopt 
    new PrimitiveType Dims ArrayInitializer 
    new ClassOrInterfaceType Dims ArrayInitializer 
+1

你不是指'只能使用它......',是嗎? – 2012-04-12 03:51:08

+1

在這句「所以,你可以只用它作爲數組創建表達式的一部分」,我可以知道你指的是'it'嗎? – noMAD 2012-04-12 03:53:09

+0

@userunknown,只是一個錯字,謝謝 – 2012-04-12 03:55:25