簡體   English   中英

將數組作為Java中的方法參數傳遞

[英]Passing arrays as method parameters in Java

以下代碼在Java中使用String的簡單數組。

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" });

但編譯器抱怨“非法開始表達而不是聲明”為什么?

根據Java語言規范( 10.6。陣列初始化器

可以在聲明中指定數組初始值設定項,也可以將其作為數組創建表達式(第15.10節)的一部分,創建數組並提供一些初始值:

因此,只有兩種方法可以使用數組初始值設定項( {"foo", "bar"} ):

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

您不能將數組初始值設定項用作方法參數。

15.10。 數組創建表達式

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM