2010-03-07 71 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