Java:Variable argument lists
1 class A { 2 } 3 4 public class NewVarArgs { 5 6 static void printArray(Object... args) { 7 for (Object obj : args) { 8 System.out.print(obj + " "); 9 } 10 System.out.println(); 11 } 12 13 public static void main(String[] args) { 14 printArray(new Integer(67), new Double(78.0)); 15 printArray(67, 455.33f, 54.54); 16 printArray("ads", "asdas", "asdasd"); 17 printArray(new A(), new A(), new A()); 18 printArray();//可以为空 19 } 20 }
输出
67 78.0
67 455.33 54.54
ads asdas asdasd
A@c17164 A@1fb8ee3 A@61de33
另一个例子
1 public class OptionalTrailingArguments { 2 static void f(int required,String...trailing){ //参数类型不一样 3 System.out.print("required: "+required+" "); 4 for(String s:trailing){ 5 System.out.print(s+" "); 6 } 7 System.out.println(); 8 } 9 public static void main(String[]args){ 10 f(1,"one"); 11 f(2,"two","three"); 12 f(3); 13 } 14 }
required: 1 one required: 2 two three required: 3