2011-06-01 22 views
0
public void foo(Integer... ids) { 
    Integer... fIds = bar(ids); 
} 

public void bar(Integer... ids) { 
// I would like to eliminate few ids and return a subset. How should I declare the return argument 
} 

我該如何聲明bar的返回類型?我該如何聲明一個可變參數

+2

我不認爲行'整數... FIDS =杆(IDS);'是合法的。 – trutheality 2011-06-01 07:57:49

回答

3

您可以參考可變參數作爲數組。

public Integer[] bar(Integer... ids) { 
.. 
} 

varargs docs

它仍然是真實的多參數必須在陣列中已過,但可變參數功能自動化和隱藏進程

到JVM這實際上是一個數組,編譯器隱藏了數組的創建。

2

bar的返回類型設置爲Integer[]並且foofIds類型指定爲Integer[]

1

變量參數參數只是數組的語法糖,因此您可以將ids作爲Integer(即Integer[])的數組來處理。

1

類似的東西:

public Integer[] bar(Integer... ids) { 
    List<Integer> res = new ArrayList<Integer>(); 
    for (Integer id : ids) 
     if (shouldBeIncluded(id)) res.add(id); 
    return res.toArray(); 
} 
相關問題