Make methods that have unspecified number of parametersTag(s): Language
You can pass an array of Objects.
public class Howto {
public static void main(String args[]) {
Howto howto = new Howto();
howto.myMethod
( new Object[] {"value 1", new Integer(2), "value n"} );
}
public void myMethod(Object parms[]) {
for (int i=0; i < parms.length; i++)
System.out.println(parms[i]);
}
}With JDK1.5+, a better approach is use VARARGS parameters.
public class TestIt {
public static void main(String ... args) {
for(String arg:args) {
System.out.println(arg);
}
}
/*
output :
>java TestIt 1 2 3 how-to
1
2
3
how-to
*/
}
public class Misc {
public static void main(String args[]){
System.out.println(Misc.sum(30,3,3,6)); // output 42
}
public static int sum(int num, int... nums) {
int total = num;
for(int n: nums) total += n;
return total;
}
}
System.out.println(Misc.sum()); // Fails with
// "The method sum(int, int...) in the type Misc is not applicable for the arguments ()
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com