This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Could you please clarify my doubts related to below question
If I compile this program , I am getting below compilation errors.
VarArgsTest.java:9: reference to doArgs is ambiguous, both method doArgs(int...) in VarArgsTest and method doArgs(java.lang.Integer...) in VarArgsTest match
VarArgsTest.java:11: reference to doArgs is ambiguous, both method doArgs(int...) in VarArgsTest and method doArgs(java.lang.Integer...) in VarArgsTest match
vat.doArgs(new Integer(1),new Integer(2));
If I do coment the any one of doArgs(int...) , doArgs(java.lang.Integer...) method , it is compiling and running fine. My doubt is that why is compiler treating doArgs(Integer i) and doArgs(int i) are different. In that case doArgs(int...) , doArgs(java.lang.Integer...) should be treated as different. Can you please explain.
Or if you find those golden rules confusing or overkill, read the following:
The algorithm used by the compiler for the resolution of overloaded methods incorporates the following phases:
1. It first perform an overloaded resolution without using any boxing, unboxing, widening or varargs.
2. If the phase 1 fails then compiler tries to find a match by using boxing, unboxing or widening but exclude varargs.
3. If phase 2 failes too, then the compiler look at the varargs methods and tries to find a match for the method call combine boxing, unboxing and widening.
So you see, when the compiler looking at the varargs methods, it already passed phase 2 which means that now using box/unbox/widening or not using box/unbox/widening is the same for the compiler when it comes to varargs. So basically for the compiler boxing and then call a vararg method is the same as just using the vararg method and none of those has any precedence/preference to each other.
If you learn the above three steps, you never be confused by such those questions. Var-Args methods comes with a bunch of tricky points and this is one of them.
Joined: Feb 27, 2009
You are right Morteza , Golden rules are not easy to understand and killing my mind.
What ever rules you mentioned are easy to capture and remember. Thanks for your reply