Jump to Real's How-to Main page

Make methods that have unspecified number of parameters

You 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]);
   }
}

NOTE : In JDK1.5, we have VARARGS parameters so this not needed anymore!

public class TestIt {
 public static void main(String args[]) {
   TestIt.doit
       (  "value 1", new Integer(2), "value n" );
   /*
   output :
   value 1
   2
   value n
   */
 }

 public static void doit(Object ... parms) {
   for(Object parm:parms) {
      System.out.println(parm);
   }
 }
}

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
  */ 
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]