Methods Allow Variable-Length Parameter Lists

     

Varargs . Yes, that is what passes for a word these days (did you ever read Ray Bradbury's "The Sound of Thunder"?). The vararg is a thing that they have in C# and other languages and it means that you stomp your foot and say, "This method has a bunch of parameters and I just don't know how many parameters a client might want to pass it, all right? " It means "variable length argument list."

This is an easy concept to start working with. The following class defines a method that accepts a vararg, and invokes the same method passing it first several arguments and then fewer arguments. The arguments come in as an array.

 

 package net.javagarage.varargs; /* Demos how to use variable length argument lists. */ public class DemoVarargs { public static void main(String...ar) {    DemoVarargs demo = new DemoVarargs();    //call the method    System.out.println(demo.min(9,6,7,4,6,5,2));    System.out.println(demo.min(5,1,8,6)); } /*define the method that can accept any number of arguments. do so using the ... syntax. Just calculates the smallest numeric value in the argument list. */ public int min(Integer...args) {       boolean first = true;       Integer min = args[0];       for (Integer i : args) {          if (first) {             min = i;             first = false;          } else if (min.compareTo(i) > 0) {             min = i;          }       }    return min; } } 

The output is

 

 2 1 

Varargs are shortcuts that prevent the programmer from having to define the method parameter as an array. You'll notice that because the main method that starts Java applications is defined to accept an array of String objects as arguments, it can also be called using this syntax, like this:

 

 public static void main(String...args) {...} 

But that is not because the main method wants an array because it just really enjoys having arrays around to hang out with. The String[] argument is required because we don't know at compile time how many arguments the user will pass into the java command.

The benefit to varargs is that your intentions are explicit (always good), and that you don't have to worry about falling off the end of the array. When combined with the for each loop as earlier, varargs are very easy to use.

So obviously, you want to accept an array as a parameter if you're going to be doing something with arrays. Use varargs only to indicate a variable length parameter list.

Note that varargs are new to SDK 5.0, so you need to compile for that version of Java to use them.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net