Java神奇的装箱与拆箱

神奇吧,对int类型的数装箱后的比较,在-128~128之间的数用==返回值是true,超出这个范围返回值是false

package com.coderbean.test;
/**
 * 测试自动装箱和拆箱
 * @author chang
 *
 */
public class Test02
{
    public static void main(String[] args)
    {
        Integer a = 1000;
        //JDK1.5之后,自动装箱。编译优化后为:Integer a = new Integer(1000);
        Integer b = 2000;
        int c = b;
        //自动拆箱。编译优化后为:int c = new Integer(1500).intValue();
        System.out.println(c);
        
        Integer d = 1234;
        Integer d2 = 1234;
        
        System.out.println(d==d2);//输出false
        System.out.println(d.equals(d2));//输出true
        
        System.out.println("###########");
        
        Integer d3 = 123; //[-128,127]之间的数,让然当做基本数据类型来处理,可以提高效率
        Integer d4 = 123;
        System.out.println(d3==d4);//输出true
        System.out.println(d3.equals(d4));//输出true
    }
}

 

原文地址:https://www.cnblogs.com/coderbean/p/4654325.html