2016-02-26 64 views
-4

我熟悉Java中的數組。我知道String[] args是指String的數組。 String... args是做什麼用的?我已經看到了參數列表是String ... args的方法,並且在該方法中,arg以arr [0],arr [1]等方式訪問,就像數組一樣。所以我的問題是,我們可以用這種方法替換String... argsString[] args嗎?如果不是,那麼這兩件事情有什麼不同?Java中的String []和(String ... args)有什麼區別?

+0

請參考這個鏈接的說明。 http://stackoverflow.com/questions/2367398/what-is-the-ellipsis-for-in-this-method-signature –

回答

0
public void dummyMethod(String... arrs) { 
    // do something 
    // arrs is an array (String[]) internally 
    System.out.println(arrs[0]); 
} 

dummyMethod("anystring1", "anystring2", "anystring3"); //this will work fine 

// OR this will work fine too 
dummyMethod(new String[]{ "anystring1", "anystring2", "anystring3" }); 

// OR without passing any args . this will also work fine.. 
dummyMethod(); 

見相差太大編譯這些之後...我只是把這樣一個例子。我剛纔也提到的評論只是看到不同的自己......

public void dummyMethod(String[] arr1) { 
    System.out.println(arr1[0]); 
} 

// this method will work correctly 
dummyMethod(new String[]{ "anystring1", "anystring2", "anystring2" }); 

// but type of calling Raise an compilation error!!! 
dummyMethod("anystring1", "anystring2", "anystring3"); 
相關問題