[英]Generic variable number of parameter passing in java
我有一個方法findByProperties(參數... p); 所以它可以采取任何數量的參數。 但我感到困惑的是,如果我不得不調用這個方法,我不知道參數的數量,我該怎么做
假設我有一個帶參數的列表,每次調用方法時列表的大小都會改變,我如何將列表中的參數添加到方法調用中?
for(ArrayList<Parameter> p : list){
findByProperties(p); //not sure what to do here
}
編輯:
這是解決方案:
Parameter[] paramArray = new ArrayList<Parameter>().toArray(new Parameter[]{});
findByProperties(paramArray);
你可以這樣做:
Parameter[] paramArray = new ArrayList<Parameter>().toArray(new Parameter[]{});
findByProperties(paramArray);
它與以下內容相同:
findProperties(param1, param2);
因為Java在內部將varargs-list轉換為數組,所以您也可以傳遞數組。
您可以覆蓋findByProperties
以采用varargs或List<Parameter>
。 然后可以轉發到另一個:
void findByProperties(Parameter... p) {
findByProperties(Arrays.asList(p));
}
void findByProperties(List<Parameter> p) {
. . .
}
然后,您可以使用Parameter
對象的變量參數列表或List<Parameter>
參數調用findByProperties
。 使用Arrays.asList
不會創建新數組; 它只是將現有數組包裝在List
實現中; 因此,這比從列表中創建新的Parameter[]
數組要少。
方法可以聲明一個從零到多個參數接受的參數,即所謂的var-arg方法。
var-arg參數用sintax類型... name; 例如:
doSomething(int ... x){}
在Java中,您還可以為具有可變參數的方法傳入數組。 因此,您可以使用參數列表的toArray
方法將List<Parameter>
轉換為Parameter[]
,它可以直接傳遞給findByProperties
:
for (ArrayList<Parameter> p : list){
Parameter[] param = p.toArray(new Parameter[p.size()])
findByProperties(param);
}
如果你還需要在其他地方這樣做,你也可以做一個方便的方法:
public ... findByProperties(List<Parameter> p) {
return findByProperties(p.toArray(new Parameter[p.size()]));
}
findByProperties(參數... p);
你可以調用方法findByProperties(); (或)findByProperties(p);
但不是findByProperties(p,p,p);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.