Boxing+Varargs is preferred over Boxing+Widening

别来无恙 提交于 2019-12-02 15:49:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!