【问题标题】:why int type value is not boxed as Integer [duplicate]为什么 int 类型值没有装箱为 Integer [重复]
【发布时间】:2013-02-07 20:20:45
【问题描述】:
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”。

只能告诉我为什么它不是“整数”,因为在 Java 中,int 值应该是自动装箱的。

【问题讨论】:

    标签: java


    【解决方案1】:

    当编译器可以选择将int 扩展为long 或将int 装箱为Integer,它会选择最便宜的转换:扩展为long。方法调用上下文中的转换规则在section 5.3 of the Java language specification 中描述,当有多个潜在匹配时选择匹配方法的规则在section 15.12.2 中描述(特别是section 15.12.2.5,但要注意这是非常密集的阅读)。

    【讨论】:

      【解决方案2】:

      这些只接受 integer 类的实例用于您的测试方法,它不是 java 的原始整数类型。 Integer 是 java 的一个类,而不是像 String 类的基本类型 int。另一方面,long 是原始类型,它具有int 的子集,因此它选择了该参数,因为它是最接近的匹配项。您也可以尝试使用双参数。当方法参数中缺少 int 或 long 签名时,它选择使用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); 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-16
        • 2015-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多