Which method is called? (Integer… a) vs. (int a, int b)

后端 未结 5 557
无人共我
无人共我 2021-02-05 06:10

I just found out about a very interesting Java trick:

void method1(Integer... a){
}

So you can give this method as many integers as you want.

相关标签:
5条回答
  • 2021-02-05 06:42

    I'm half guessing, but like thinksteep said, Integer... is actually treated as an Integer array, which implies that your method call would have to do two coercions to make it match the first method (boxing the ints to Integers, and treating your argument list as an array rather than simply two different arguments). Whereas, no coercions are required to make it match the second method.

    OK, I can see several others have already quoted the JLS with more specificity than I have provided, while I was typing this out.

    0 讨论(0)
  • 2021-02-05 06:46

    A call will made to method1(int a, int b) . Just checked byte code for this - here Integer... a is actually an Integer[] a For a detailed conversion check these assignment conversion

    0 讨论(0)
  • 2021-02-05 06:47

    The second method wins. According to the Java Language Specification (pdf),

    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 an applicable method is found during this stage, that method wins; no further search is performed. In your case, it happens to be the second method, because the first one is a variable arity method that also requires boxing.

    0 讨论(0)
  • 2021-02-05 06:49

    varargs has the least priority. If no other matched method found then only it gets called.It is just like the default case of SWITCH case.

    0 讨论(0)
  • 2021-02-05 06:50

    To determine which method should be called, the compiler goes through the following list, as detailed in the JLS #5.3 and JLS #15.12.2:

    • an identity conversion (§5.1.1) => method1(int a, int b)
    • a widening primitive conversion (§5.1.2)
    • a widening reference conversion (§5.1.5)
    • a boxing conversion (§5.1.7) optionally followed by widening reference conversion ==> method1(Integer... a)
    • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

    In your case, the first point applies and method1(int, int) is called.

    (To be more precise, your method uses varags and has a lower priority than a simple boxing conversion. In other words, if there were a method1(Integer a, Integer b) it would come before method1(Integer... a) in the hierarchy)

    Why is it so? A comment in 15.12.2 give a hint:

    This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing.

    0 讨论(0)
提交回复
热议问题