Joe
Joe

Reputation: 15341

How should I declare a variable argument parameter

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 
}

How should I declare the return type for bar?

Upvotes: 0

Views: 1200

Answers (4)

Bozho
Bozho

Reputation: 597114

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.

Upvotes: 3

Xion
Xion

Reputation: 22770

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();
}

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308051

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

Upvotes: 1

hsz
hsz

Reputation: 152226

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

Upvotes: 2

Related Questions