What is the output of the following result.
class Main { /*from ww w .j a v a 2s. c o m*/ static void myTest(int ... v) { System.out.print("myTest(Integer ...): " + "Number of args: " + v.length + " Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); } static void myTest(boolean ... v) { System.out.print("myTest(boolean ...) " + "Number of args: " + v.length + " Contents: "); for(boolean x : v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { myTest(); myTest(1, 2, 3); myTest(true, false, false); } }
class Main { static void myTest(int ... v) { System.out.print("myTest(Integer ...): " + "Number of args: " + v.length + " Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); } static void myTest(boolean ... v) { System.out.print("myTest(boolean ...) " + "Number of args: " + v.length + " Contents: "); for(boolean x : v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { myTest();//Error // myTest(1, 2, 3); //OK // myTest(true, false, false); //OK } }
It is possible to create an ambiguous call to an overloaded varargs method.
In this program, the overloading of myTest()
is perfectly correct.
However, this program will not compile because of the following call:
myTest();
Because the vararg parameter can be empty, this call could be translated into a call to myTest(int...)
or myTest(boolean...)
.
Both are equally valid.