I am getting a compile time error when I type this code out:
public void myMethod(Foo... f, Bar... b) {
}
It says that the varargs has to be the last argument, is there any other way to implement this kind of functionality?
I am getting a compile time error when I type this code out:
public void myMethod(Foo... f, Bar... b) {
}
It says that the varargs has to be the last argument, is there any other way to implement this kind of functionality?
This is not possible because there is no way the second argument is determined.
To understand why it should be the last argument, Consider your method
public void myMethod(Foo... f, Foo f1){}
Now suppose you call it using myMethod(fooObj1, fooObj2, fooObj3);
All the foo arguments will be applied for the var-arg method parameter. Hence there is no way to tell a specific object is passed as the second argument.
Now when you keep the var-arg as the last parameter,
public void meMethod(Foo f1, Foo... f){}
The method call myMethod(fooObj1, fooObj2, fooObj3);
will assign fooObj1
to f1 and fooObj2
and fooObj3
will be applied to the var-arg f
To solve this problem, you will have to do
public void myMethod(Foo[] f, Bar... b) {
}
Not possible, you would have to do
public void myMethod(Foo[] f, Bar... b) {
}
as a workaround.
You can have only one varargs in a method. Varargs must be the last formal parameter.
Try with
public void myMethod(Foo[] f, Bar... b) {
}
Only one varargs
argument is allowed in java and it must be the last parameter of the signature.Multiple vararg
arguments can lead to ambiguity
as you may get confused where the 1st one ends and where the second one begins.
varargs
gets converted to an array, so you can simply pass two arrays instead.
That's one of Java's rule, in a method signature, you can have only one vararg, and at the end of the arguments list.
From the "SCJP Sun Certified Programmer for Java", here are the valid and invalid methods signatures:
// Legal:
// expects from 0 to many ints as parameters
void doStuff(int... x);
// expects first a char, then 0 to many ints
void doStuff2(char c, int... x);
// 0 to many Animals
void doStuff3(Animal... animal);
// Illegal:
// bad syntax
void doStuff4(int x...);
// too many var-args
void doStuff5(int... x, char... y);
// var-arg must be last
void doStuff6(String... s, byte b);
If you absolutely want some Foo and Bar and if they have something in common, maybe you can have method like
public void myMethod(CommonParentClassOrInterface... f);
and do some check on the actual class of each of them, but you'll have no guaranty that you'll get Foo's first and then Bar's.
I haven't really used the varargs a lot though, it's just a suggestion, but I may be wrong.