Java自动装箱与拆箱

问题

题目引入,结果是什么?

	public static void main(String[] args) {
        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        System.out.println(c == d);
        System.out.println(e == f);
        System.out.println(c == (a + b));
        System.out.println(c.equals(a + b));
        System.out.println(g == (a + b));
        System.out.println(g.equals(a + b));
    }

如果对答案不明确,或者不知道答案,可以通过阅读这篇文章解答疑惑。

自动装箱

定义

在定义一个Integer类型的对象时,我们是直接通过Integer i = 100,这样去定义。我们知道这样定义是允许的,但是仔细思考一下,i 是Integer类型的引用,100是基本数据类型int。所以,这是jdk提供的语法糖,这就是自动装箱。
在1.5之前,定义对象只能是通过Integer i = new Integer(100)来完成。

原理

自动拆装箱,是jdk提供的语法糖,是在编译后,就会翻译成原始的代码,我们可以通过class文件查看下。

	Integer i = 100; 
	
	//反编译字节码结果是
	Integer i = Integer.valueOf(100);

通过断点,可以考到i的赋值语句,经过了

	/**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
    	//这个if很关键,稍后讲解
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

总结: 自动装箱是包装类型指向基本类型时,会自动调用valueOf方法,完成数据的封装。

拆箱

定义
	Integer integer100=100;
	int int100=integer100;

在上面的代码中,定义了引用类型integer100,和基本类型int100,但是上面的操作,将引用类型,赋值给了基本数据类型,这就是自定拆箱。

原理

通过装箱,我们应该可以猜得到,自动装箱也是jdk默认做了一些操作。

/**
     * Returns the value of this {@code Integer} as an
     * {@code int}.
     */
    public int intValue() {
        return value;
    }

也就是,jdk帮我们完成了对intValue()方法的调用。对于以上的实验而言,便是调用integer100的intValue()方法,将其返回值赋给了int100。

练习

实验1

当一个包装类型和基本类型用 == 比较,是进行装箱,还是拆箱?

 	//包装类型和基本类型用==比较,是拆箱,还是装箱
    @Test
    public void demo1() {
        int int400 = 400;//数值大于127
        Integer integer400 = 400;
        System.out.println(int400 == integer400);
    }

== 运算,对于对象比较的是地址值,对于基本数据类型,比较的是数值。推测下结果,如果是int400装箱了,则返回的结果是false,因为是两个不同的对象地址值。如果是integer400拆箱了,则返回true,进行数值比较。
结果返回的是true,int400是int基本类型,Integer400是引用类型,在进行 == 比较时候,integer400拆箱了。

实验2
	//自动装箱操作
    @Test
    public void demo2() {
        Integer integer200 = 200;
        int int200 = 200;
        System.out.println(integer200.equals(int200));
    }

判断结果是什么? 先来分析一下,integer200是包装类型,他的equals()方法,传入的是个对象,所以int200会进行自动装箱操作,转换为包装类型。所以这时候会思考了,integer200和int200的包装类型对象,不是同一个对象,两个地址指不相等,所以返回结果应该是false,其实答案是返回true。前面分析int200是正确的,错误的是equals方法,Integer重写了equals方法,使其比较的是对象类型和数值大小,不是地址值了。

	public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
实验3

如果是进行 + -等其他运算呢,基本数据类型和包装类型,是会发生装箱还是拆箱。

	
	// + -运算,是拆箱还是装箱了
    @Test
    public void demo3() {
        int int100 = 200;
        Integer integer100 = 200;
        Long Long400 = 400l;
        System.out.println(Long400 == (int100 + integer100));
        System.out.println(Long400.equals(int100 + integer100));
    }

分析测试题目,看得到,int100+integer100 与Long400进行 == 比较,前面测试知道,如果 两个对象进行=比较,则是地址值比较,如果是基本类型和包装类型,则会发生拆箱,进行数值比较。所以,如果(int100 + integer100)拆箱了,则返回结果是true,否则是int100装箱。对于第二个输出,equals传入的一定是对象。
结果分析: true false
第二个是false,是肯定的,无论(int100 + integer100)是拆箱还是装箱,最后传入的都得是Integer对象,两者类型不一样,返回的肯定是false。
第一个是true,只可能是(int100 + integer100)拆箱,然后Long400 == 400 又进行了一次拆箱,才会返回true,所以得出结论, 四则元素,如果是包装类型数据,会拆箱进行运算
这里Long400.equals(int100 + integer100),先进行了拆箱,后装箱。

注意
	Integer integer100=null;
	int int100=integer100;

这种使用会发生空指针异常,对于包装类型定义为null是可以的,但是int100去接收null的包装类型,会调用intValue(),但是对象是null,则会失败。

	Integer i1=100;
	Integer i2=100;
	Integer i3=300;
	Integer i4=300;
	System.out.println(i1==i2);//true
	System.out.println(i3==i4);//false

i3==i4返回false是没问题吧,两者都是不同的对象,地址值不是相同的。
对于i1和i2则是false,是因为,i1和i2是同一个对象。

	//自动装箱操作,如果i在-128到127之间,则会在IntegerCache中获取
	public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

	private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

我们可以清楚地看到,IntegerCache有静态成员变量cache,为一个拥有256个元素的数组。在IntegerCache中也对cache进行了初始化,即第i个元素是值为i-128的Integer对象。而-128至127是最常用的Integer对象,这样的做法也在很大程度上提高了性能。也正因为如此,“Integeri1=100;Integer i2=100;”,i1与i2得到是相同的对象。

最后结果

	public static void main(String[] args) {
        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        System.out.println(c == d);//t c和d在127之内,指向同一个对象
        System.out.println(e == f);//f e f在128之外,装箱是为每个数值封装成对象
        //a+b是拆箱,运算后是整数3 c==3,进行了拆箱,数值一样,返回true
        System.out.println(c == (a + b));//t    
        //a+b拆箱后运算结果3,然后装箱,传入equals运算,比较对象类型和数值大小
        System.out.println(c.equals(a + b));//t 
        //a+b拆箱结果3,g是Long拆箱为数值3,比较相等
        System.out.println(g == (a + b));//t
        //a+b是3,然后3装箱为包装类型,g是Long,3包装类型是Integer,两者不等
        System.out.println(g.equals(a + b));//f
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值