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
  */
}
The ellipsis … means that you can pass 0 or more parameters. If you prefer to force 1 parameter or more then you can add 1 parameter followed by the VARARGS parameter to the signature.
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;
   }
}
The advantage is if you try to call the method with no parameter then the call will fail at compile time and not runtime.
System.out.println(Misc.sum()); // Fails with
                                // "The method sum(int, int...) in the type Misc is not applicable for the arguments ()

blog comments powered by Disqus