自动装箱和自动拆箱

自动装箱和自动拆箱

//自动装箱、自动拆箱
public class AutoBox {
    public static void main(String[] args) {
        Integer a = 100;
        // 相当于编译器自动为你做以下的语法便宜:
        // Integer a = Integer.valueOf(100);调用的不是 new Integer(100)
        int b = a;
        //相当于 int b = a.intValue();

        //Integer 缓存问题
        Integer i1 = -128;
        Integer i2 = -128;
        System.out.println(i1==i2);
        System.out.println(i1.equals(i2));
        System.out.println("----------------------");
        Integer i3 = 1234;
        Integer i4 = 1234;
        System.out.println(i3==i4);
        System.out.println(i3.equals(i4));
        /* 结果
        true
        true
        ----------------------
        false
        true
        应为Integer 系统初始时会创建个缓存数组【-128~127】
        如果在这个范围内,直接从缓存数组拿,否则重新创建新的Integer对象.
         */

    }
}
posted @ 2021-03-05 22:08  坚持出成绩  阅读(69)  评论(0)    收藏  举报