[Java] Java中的變長引數的使用
1 基本使用方法
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.
Code below demonstrates method average (lines 7-16), 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 12-13 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.
// Fig. 7.20: VarargsTest.java
// Using variable-length argument lists.
public class VarargsTest {
// calculate average
public static double average( double... numbers ){
double total = 0.0; // initialize total
// calculate total using the enhanced for statement
for ( double d : numbers ){
total += d;
return total / numbers.length;
}
} // end method average
public static void main( String args[] ) {
double d1 = 10.0;
double d2 = 20.0;
double d3 = 30.0;
double d4 = 40.0;
System.out.printf( "d1 = %.1f\nd2 = %.1f\nd3 = %.1f\nd4 = %.1f\n\n", d1, d2, d3, d4 );
System.out.printf( "Average of d1 and d2 is %.1f\n", average( d1, d2 ) );
System.out.printf( "Average of d1, d2 and d3 is %.1f\n", average( d1, d2, d3 ) );
System.out.printf( "Average of d1, d2, d3 and d4 is %.1f\n", average( d1, d2, d3, d4 ) );
} // end main
} // end class VarargsTest
d1 = 10.0
d2 = 20.0
d3 = 30.0
d4 = 40.0
Average of d1 and d2 is 15.0
Average of d1, d2 and d3 is 20.0
Average of d1, d2, d3 and d4 is 25.0
2 解釋與理解
變長引數由編譯器編譯為陣列, 所以使用的時候可以按照像使用陣列一樣進行遍歷。但是如果給定某個含有變長引數的方法,會有如下特例:
someMethod(String... strings)
- 如果呼叫上面方法時候引數是
null
,即:someMethod(null)
, 那麼在方法體內,strings
的值為null - 如果呼叫上面方法的引數是多個
null
, 即:someMethod(null,null)
, 那麼方法體內,strings
的型別是class [Ljava.lang.String;
, 即String
型別的一維陣列,其值為[null, null]
- 如果不使用引數呼叫此方法,即
someMethod()
,那麼strings
在方法體內是含有空字串的字元陣列。