method calls when the arguments are unknown
I'm creating a method in my latest java program that i needs to be able to accept different amounts of arguments, but i don't know if it can be done in Java. I need to pass it 1-4 arguments, depending on where and when it is called. In C++ it would look like :
method(int arg1, ...)
Is there a way to do this in Java?
[345 byte] By [
merlyn614] at [2007-9-26 2:25:46]

One way is to use overloading:
void method(int arg1) {
// code for 1-arg method
}
void method(int arg1, int arg2) {
// code for 2-arg method
}
void method(int arg1, int arg2, int arg3) {
// code for 3-arg method
}
void method(int arg1, int arg2, int arg3, int arg4) {
// code for 4-arg method
}
or, if you know that all the args will have the same type, you can use an array instead:
void method(int[] args) {
for (int i = 0; i < args.length; ++i) {
// do something
}
}