SCJP问题:方法含糊不清

3

看一下这段代码:

public class Test {
public static void main(String... args) {
    flipFlop("hello", new Integer(4), 2004);
    // flipFlop("hello", 10, 2004); // this works!
}

private static void flipFlop(String str, int i, Integer iRef) {
    System.out.println(str + " (String, int, Integer)");
}

private static void flipFlop(String str, int i, int j) {
    System.out.println(str + " (String, int, int)");
}

}

编译器报错,调用不明确:

描述 资源 路径 位置 类型 方法flipFlop(String, int, Integer)对于类型Test是不明确的 Test.java scjp19 - inheritence/src 第3行 Java问题

但是,如果使用被注释掉的行来调用flip-flop方法,则可以明确地调用该方法(第二个方法,因为自动装箱在使用原始类型后进行)。
我期望编译器能够看到第二个参数将以某种方式取消装箱,并根据第三个参数判断必须调用哪个方法。为什么这种情况没有发生?这是什么原理?

2
重复:https://dev59.com/1XRB5IYBdhLWcg3wz6ad - BalusC
4个回答

6

注释行完全匹配 flipFlop(String str, int i, int j)。另一行由于自动装箱而匹配。


1

flipFlop("hello", new Integer(4), 2004); 与 flipFlop(String str, int i, Integer iRef) 不兼容


1
我认为这不是问题... Java 5及更高版本支持原始类型和其包装类之间的自动装箱/拆箱。在这种情况下,是int和Integer之间的转换。注释掉第二个方法,亲自试一试。 - Markos Fragkakis

0

Java 5及以上版本支持自动装箱(将Integer转换为int),因此得到了这个结果。


-1

是的,根据问题,调用应该取决于第三个参数int / Integer之间的差异。 但是,如果第二个参数是autoUnboxed,即使在第三个参数处的差异也很重要。

即使这样也可以工作: flipFlop(“hex”,new Integer(4),new Integer(17));

根据语法和自动装箱功能,这应该调用:: “private static void flipFlop(String str,int i,Integer iRef)”方法,但它所说的一切都是AMBIGUOUS .....?


1
使用完整的单词(例如acc改为according,ques改为question,@改为at)可以使您的答案更易读和有用于其他SO成员。 - Markos Fragkakis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接