Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a varargs method with an additional argument from a varargs method

I have some varargs system function, where T is some actual type, like String:

sys(T... args)

I want to create own function, which delegates to the system function. My function is also a varargs function. I want to pass through all the arguments for my function through to the system function, plus an additional trailing argument. Something like this:

myfunc(T... args) {
    T myobj = new T();
    sys(args, myobj); // <- of course, here error.
}

How do I need to change the line with the error? Now I see only one way: create array with dimension [args] + 1 and copy all items to the new array. But maybe there exists a more simple way?

like image 494
Yura Shinkarev Avatar asked Dec 04 '14 12:12

Yura Shinkarev


People also ask

How many varargs parameters can a method have?

Each method can only have one varargs parameter. The varargs argument must be the last parameter.

What is the rule for using Varargs?

Rules for varargs:There can be only one variable argument in the method. Variable argument (varargs) must be the last argument.

How do you call Varargs?

Syntax of VarargsA variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].


2 Answers

Now I see only one way: create array with dimension [args] + 1 and copy all items to new array.

There is no simpler way. You need to create a new array and include myobj as last element of the array.

String[] args2 = Arrays.copyOf(args, args.length + 1);
args2[args2.length-1] = myobj;
sys(args2);

If you happen to depend on Apache Commons Lang you can do

sys(ArrayUtils.add(args, myobj));

or Guava

sys(ObjectArrays.concat(args, myobj));
like image 130
aioobe Avatar answered Oct 04 '22 16:10

aioobe


You may call sys() twice if the order doesn't care:

T myobj=new T();
sys(myobj);
sys(args);

If you can't use this, switch to collections (eg. LinkedList) for all of your functions.

like image 40
brummfondel Avatar answered Oct 04 '22 16:10

brummfondel