2010-03-07 152 views
3

这个代码看看:SCJP问题:方法暧昧

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)"); 
} 

} 

编译器给出错误的调用不明确:

描述资源路径位置类型 方法触发器(字符串,int,Integer)对于Test Test.java类型是不明确的scjp19 - inheritence/src line 3 Java问题

但是,如果commente d-out行用于调用触发器,该方法明确地被调用(第二个,因为在使用原语本身后出现自动装箱)。

我希望编译器能够看到第二个参数将以某种方式拆箱,并根据第三个参数判断必须调用哪个方法。为什么不发生这种情况?基本原理是什么?

+2

Dupe:http://stackoverflow.com/questions/501412/why-does-autoboxing-make-some-calls-ambiguous-in-java – BalusC 2010-03-07 17:13:28

回答

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和更高版本支持在基元和它们的Wrapper类之间自动装箱/拆箱。在这个int和Integer之间的情况下。注释掉第二种方法并亲自查看。 – 2010-03-07 17:28:13

0

Java 5及更高版本会自动装箱(将Integer转换为int),从而得到结果。

-1

是的,根据问题,调用应该取决于int/Integer @ 3rd参数之间的差异。 但是如果第二个参数是autoUnboxed的话,这里即使是不同的@第3个参数也很重要。

即使这样做: flipFlop(“hex”,new Integer(4),new Integer(17));

虽然根据syntex和auto box功能,应该调用:: “私有静态void flipFlop(String str,int i,Integer iRef)”方法,但它的全部说法是AMBIGUOUS ..... ??

+1

使用完整单词(acc - >根据,ques - > question,@ - > at)将使您的答案对其他SO成员更具可读性和有用性。 – 2012-01-03 10:01:24