具有可变长度参数(Varargs)的方法可以具有零个或多个参数。另外,如果需要,可以重载Varargs方法。
演示此过程的程序如下:
public class Demo { public static void Varargs(int... args) { System.out.println("\nNumber of int arguments are: " + args.length); System.out.println("The int argument values are: "); for (int i : args) System.out.println(i); } public static void Varargs(char... args) { System.out.println("\nNumber of char arguments are: " + args.length); System.out.println("The char argument values are: "); for (char i : args) System.out.println(i); } public static void Varargs(double... args) { System.out.println("\nNumber of double arguments are: " + args.length); System.out.println("The double argument values are: "); for (double i : args) System.out.println(i); } public static void main(String args[]) { Varargs(4, 9, 1, 6, 3); Varargs('A', 'B', 'C'); Varargs(5.9, 2.5); } }
输出结果
Number of int arguments are: 5 The int argument values are: 4 9 1 6 3 Number of char arguments are: 3 The char argument values are: A B C Number of double arguments are: 2 The double argument values are: 5.9 2.5