Java使用可变参数与方法重载
如何使用方法重载处理使用可变参数作为输入?
解决方法
本示例显示如何重载具有可变参数作为输入的方法。
public class Main { static void vaTest(int ... no) { System.out.print("vaTest(int ...): " + "Number of args: " + no.length +" Contents: "); for(int n : no) System.out.print(n + " "); System.out.println(); } static void vaTest(boolean ... bl) { System.out.print("vaTest(boolean ...) " + "Number of args: " + bl.length + " Contents: "); for(boolean b : bl) System.out.print(b + " "); System.out.println(); } static void vaTest(String msg, int ... no) { System.out.print("vaTest(String, int ...): " + msg +"no. of arguments: "+ no.length +" Contents: "); for(int n : no) System.out.print(n + " "); System.out.println(); } public static void main(String args[]){ vaTest(1, 2, 3); vaTest("Testing: ", 10, 20); vaTest(true, false, false); } }
结果
上面的代码示例将产生以下结果。
vaTest(int ...): Number of args: 3 Contents: 1 2 3 vaTest(String, int ...): Testing: no. of arguments: 2 Contents: 10 20 vaTest(boolean ...) Number of args: 3 Contents: true false false