问题
Please correct me if I'm wrong. Is Boxing+Varargs is preferred over Boxing+Widening?
I found in a site that its the other way.
回答1:
What method is called when several could qualify is defined in the JLS #15.2.2:
The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.
The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.
The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.
So in summary: widening > boxing&unboxing > varargs
回答2:
Boxing + Widening is preferred over Boxing + Varargs. I have changed @John's example to show this:
public static void main(String[] args) {
int i = 2;
doX(i);
}
static void doX(Object i) {
System.out.println("Object");
}
static void doX(Integer... i) {
System.out.println("Integer...");
}
prints
Object
回答3:
Boxing+Widening is preferred over Boxing+Varargs. A simple test would confirm the same.
public static void main(String[] args) {
int i = 2;
doX(2);
}
static void doX(Object i){
System.out.println("object...");
}
static void doX(Integer... i){
System.out.println("int...");
}
Prints:
object...
EDIT: Sorry, my bad. I have corrected the code. Didn't notice I had typed "Object..."
来源:https://stackoverflow.com/questions/12510396/boxingvarargs-is-preferred-over-boxingwidening