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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步