【问题标题】:Integer instance and int primitive value comparison in JavaJava中的整数实例和int原始值比较
【发布时间】:2016-04-05 21:33:21
【问题描述】:
Integer a = 5;
int b = 5;

System.out.println(a==b); // Print true

但是为什么这打印结果为真,因为 a 是 Integer 的实例而 b 是原始 int

【问题讨论】:

标签: java


【解决方案1】:

当您比较原始类和包装类时,Java 使用Unboxing 的概念。其中Integer 变量被转换为原始int 类型。

以下是您的代码发生的情况:

Integer a = 5; //a of type Integer i.e. wrapper class
int b = 5; //b of primitive int type

System.out.println(a==b) // a is unboxed to int type and compared with b, hence true

更多关于Autoboxing(取消装箱)和Unboxingthis链接的信息。

【讨论】:

    【解决方案2】:

    从 JDK 5 开始,Java 添加了两个重要特性:自动装箱和自动拆箱。

    自动装箱是一个原始类型自动生成的过程 封装(装箱)到其等效类型包装器中,只要 需要该类型的对象。没有必要明确 构造一个对象。

    自动拆箱是一个装箱对象的值的过程 当它的值时自动从类型包装器中提取(拆箱) 需要。

    使用自动装箱,不再需要手动构造对象以 包装一个原始类型:

    Integer someInt = 100; // autobox the int (i.e. 100) into an Integer
    

    要拆箱对象,只需将该对象引用分配给原始类型变量:

    int unboxed = someInt // auto-unbox Integer instance to an int
    

    【讨论】:

      【解决方案3】:

      正确的答案是由于拆箱,但让我们在这里更明确。

      数值等价的规则在in the Java Language Specification中描述,特别是这些规则:

      如果相等运算符的操作数都是数字类型,或者一个是数字类型,而另一个是可转换(第 5.1.8 节)为数字类型,则对操作数执行二进制数字提升(第 5.6.2 节) )。

      由于Integer 可转换为数字类型(根据these rules),您要比较的值在语义上等同于a.intValue() == b

      需要强调的是,如果anull,则此转换将失败;也就是说,当您尝试进行等价检查时,您将收到 NullPointerException

      【讨论】:

        【解决方案4】:

        这里所有帖子的答案都是正确的。

        这里是编译时的代码

        public class Compare {
        
            public static void main(String[] args) {
                // TODO Auto-generated method stub
        
                Integer a=5;
                int b=5;
        
                System.out.println(a==b);
                //the compiler converts the code to the following at runtime: 
                //So that you get it at run time
                System.out.println(a==Integer.valueOf(b));
        
        
            }
        

        }

        【讨论】:

          猜你喜欢
          • 2014-02-06
          • 1970-01-01
          • 1970-01-01
          • 2014-11-07
          • 2018-05-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多