Variable-Length Argument Lists
Variable-length argument lists are a new feature in J2SE 5.0. Programmers can create methods that receive an unspecified number of arguments. An argument type followed by an ellipsis (...) in a method's parameter list indicates that the method receives a variable number of arguments of that particular type. This use of the ellipsis can occur only once in a parameter list, and the ellipsis, together with its type, must be placed at the end of the parameter list. While programmers can use method overloading and array passing to accomplish much of what is accomplished with "varargs," or variable-length argument lists, using an ellipsis in a method's parameter list is more concise.
Figure 7.20 demonstrates method average (lines 716), which receives a variable-length sequence of doubles. Java treats the variable-length argument list as an array whose elements are all of the same type. Hence, the method body can manipulate the parameter numbers as an array of doubles. Lines 1213 use the enhanced for loop to walk through the array and calculate the total of the doubles in the array. Line 15 accesses numbers.length to obtain the size of the numbers array for use in the averaging calculation. Lines 29, 31 and 33 in main call method average with two, three and four arguments, respectively. Method average has a variable-length argument list, so it can average as many double arguments as the caller passes. The output reveals that each call to method average returns the correct value.
Figure 7.20. Using variable-length argument lists.
(This item is displayed on pages 322 - 323 in the print version)
1 // Fig. 7.20: VarargsTest.java 2 // Using variable-length argument lists. 3 4 public class VarargsTest 5 { 6 // calculate average 7 public static double average( double... numbers ) 8 { 9 double total = 0.0; // initialize total 10 11 // calculate total using the enhanced for statement 12 for ( double d : numbers ) 13 total += d; 14 15 return total / numbers.length; 16 } // end method average 17 18 public static void main( String args[] ) 19 { 20 double d1 = 10.0; 21 double d2 = 20.0; 22 double d3 = 30.0; 23 double d4 = 40.0; 24 25 System.out.printf( "d1 = %.1f d2 = %.1f d3 = %.1f d4 = %.1f ", 26 d1, d2, d3, d4 ); 27 28 System.out.printf( "Average of d1 and d2 is %.1f ", 29 average( d1, d2 ) ); 30 System.out.printf( "Average of d1, d2 and d3 is %.1f ", 31 average( d1, d2, d3 ) ); 32 System.out.printf( "Average of d1, d2, d3 and d4 is %.1f ", 33 average( d1, d2, d3, d4 ) ); 34 } // end main 35 } // end class VarargsTest
|
Common Programming Error 7.6
Placing an ellipsis in the middle of a method parameter list is a syntax error. An ellipsis may be placed only at the end of the parameter list. |