2008-11-19 100 views

回答

78

兩者之間唯一的區別就是您調用函數的方式。使用String var args可以省略數組創建。

public static void main(String[] args) { 
    callMe1(new String[] {"a", "b", "c"}); 
    callMe2("a", "b", "c"); 
    // You can also do this 
    // callMe2(new String[] {"a", "b", "c"}); 
} 
public static void callMe1(String[] args) { 
    System.out.println(args.getClass() == String[].class); 
    for (String s : args) { 
     System.out.println(s); 
    } 
} 
public static void callMe2(String... args) { 
    System.out.println(args.getClass() == String[].class); 
    for (String s : args) { 
     System.out.println(s); 
    } 
} 
6

在接收器大小上,您將得到一個String數組。區別僅在於主叫方。

7

你打電話的第一個函數爲:

function(arg1, arg2, arg3); 

,而第二個:

String [] args = new String[3]; 
args[0] = ""; 
args[1] = ""; 
args[2] = ""; 
function(args); 
8

可變參數(String...),你可以調用的方法是這樣的:

function(arg1); 
function(arg1, arg2); 
function(arg1, arg2, arg3); 

Y ou不能這樣做與數組(String[]

+0

我最喜歡的答案 – 2014-03-05 14:00:11

17

區別只在調用該方法時。第二種形式必須用一個數組來調用,第一種形式可以用一個數組來調用(就像第二種形式一樣,是的,這是根據Java標準有效的)或者一串字符串(用逗號分隔的多個字符串)或根本沒有參數(第二個總是必須有一個,至少必須通過null)。

它是語法上的糖。實際上,編譯器開啓

function(s1, s2, s3); 

function(new String[] { s1, s2, s3 }); 

內部。

2
class StringArray1 
{ 
    public static void main(String[] args) { 
     callMe1(new String[] {"a", "b", "c"}); 
     callMe2(1,"a", "b", "c"); 
    callMe2(2); 
     // You can also do this 
     // callMe2(3, new String[] {"a", "b", "c"}); 
} 
public static void callMe1(String[] args) { 
     System.out.println(args.getClass() == String[].class); 
     for (String s : args) { 
      System.out.println(s); 
     } 
    } 
    public static void callMe2(int i,String... args) { 
     System.out.println(args.getClass() == String[].class); 
     for (String s : args) { 
      System.out.println(s); 
     } 
    } 
}