Compiler error : reference to call ambiguous

前端 未结 6 1841
無奈伤痛
無奈伤痛 2020-11-29 09:07

Case 1

static void call(Integer i) {
    System.out.println(\"hi\" + i);
}

static void call(int i) {
    System.out.println(\"hello\" + i);         


        
6条回答
  •  抹茶落季
    2020-11-29 09:51

    If more than one method can be applicable, than from the Java Language Specification we Choosing the Most Specific Method, paragraph 15.12.2.5:

    One variable arity member method named m is more specific than another variable arity member method of the same name if either (<: means subtyping):

    1. One member method has n parameters and the other has k parameters, where n ≥ k, and:
      • The types of the parameters of the first member method are T1, ..., Tn-1, Tn[]. (we have only one T_n[], which is Integer[], n=1)
      • The types of the parameters of the other method are U1, ..., Uk-1, Uk[]. (again only one paramenter, which is int[], k=1)
      • If the second method is generic then let R1 ... Rp (p ≥ 1) be its type parameters, let Bl be the declared bound of Rl (1 ≤ l ≤ p), let A1 ... Ap be the type arguments inferred (§15.12.2.7) for this invocation under the initial constraints Ti << Ui (1 ≤ i ≤ k-1) and Ti << Uk (k ≤ i ≤ n), and let Si = Ui[R1=A1,...,Rp=Ap] (1 ≤ i ≤ k). (method is not generic)
      • Otherwise, let Si = Ui (1 ≤ i ≤ k). (S1 = int[])
      • For all j from 1 to k-1, Tj <: Sj, and, (nothing here)
      • For all j from k to n, Tj <: Sk, and, (Compare T1 <: S1, Integer[] <: int[])
      • If the second method is a generic method as described above, then Al <: Bl[R1=A1,...,Rp=Ap] (1 ≤ l ≤ p). (method is not generic)

    Although primitive int is autoboxed to wrapper Integer, int[] is not autoboxed to Integer[], than the first condition doesn't hold.

    Second condition is almost the same.

    There are also other conditions that do not hold, and then due to JLS:

    we say that the method invocation is ambiguous, and a compile-time error occurs.

提交回复
热议问题