2013-02-07 272 views
4
public class Test { 
static void test(Integer x) { 
    System.out.println("Integer"); 
} 

static void test(long x) { 
    System.out.println("long"); 
} 

static void test(Byte x) { 
    System.out.println("byte"); 
} 

static void test(Short x) { 
    System.out.println("short"); 
} 

public static void main(String[] args) { 
    int i = 5; 
    test(i); 
} 
} 

輸出值是「long」。int類型值爲什麼不是整數

只能告訴我爲什麼它不是「Integer」,因爲在Java中,int值應該是自動裝箱的。

回答

14

當編譯器具有加寬的intlong或拳擊的int作爲Integer的選擇,它選擇最便宜的轉換:加寬到long。在方法調用的上下文中的轉換規則在section 5.3 of the Java language specification中描述,並且在section 15.12.2(特別是section 15.12.2.5,但被警告這是非常密集的閱讀)中描述了當存在多個潛在匹配時選擇匹配方法的規則。

0

這些只接受您的測試方法的integer類的實例,它不是Java的原始整數類型。 Integer是一類java不是原始類型int類似String類。另一方面,long是一種原始類型,它具有int的子集,所以它選擇該參數,因爲它是最接近的匹配。你也可以嘗試使用雙參數。當int或long是signature方法中的缺失時,它選擇使用double的方法參數,因爲它是最接近的匹配項。

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html

試試這個:

public static void main(String[] args) { 
    int i = 5; 
    test(i); 

    Integer smartInt= new Integer(5); 
    test(smartInt); 
} 
相關問題