开发者

How should I declare a variable argument parameter

开发者 https://www.devze.com 2023-03-10 02:20 出处:网络
public void foo(Integer... ids) { Integer... fIds = bar(ids); } public void bar(Integer... ids) { // I would l开发者_开发技巧ike to eliminate few ids and return a subset. How should I declare the ret
public void foo(Integer... ids) {
    Integer... fIds = bar(ids);
}

public void bar(Integer... ids) {
// I would l开发者_开发技巧ike to eliminate few ids and return a subset. How should I declare the return argument 
}

How should I declare the return type for bar?


You can refer to vararg parameters as an array.

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

See varargs docs

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process

To the jvm this is actually an array, and the compiler has hidden the creation of the array.


Set bar's return type to Integer[] and in foo specify fIds type as Integer[] too.


Variable arguments parameters are just syntactic sugar for arrays, so you can just handle ids as an array of Integer (i.e. an Integer[]).


Something like that:

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

精彩评论

暂无评论...
验证码 换一张
取 消