java拆箱测验

Integer a = 1;
	Integer b = 2;
	Integer c = 3;
	Integer d =3;
	Integer e = 127;
	Integer f = 127;
	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));


 

结果

true
true
true
true
true
false

 

Integer e = 128;Integer f = 128; 结果为false

原因:==比较地址相等, 不会自动拆箱,但遇到运算是会发生:  如c=(a+b) ,g==(a+b)会发生Integer.intvavlue方法的底层调用拆箱,所以为true

 

2.valueof

a对象是调用Integer.valueOf()生成的,b是通过自动装箱生成的对象,为什么会是同一个对象呢?再看一下字节码吧,毕竟Java程序是依靠虚拟机运行字节码实现的。

m41这个方法只适用了一次valueOf(),但字节码中出现了两次,说明自动装箱时也调用了valueOf()

下面是valueOf()具体实现

    /**

     * Returns a <tt>Integer</tt> instance representing the specified

     * <tt>int</tt> value.

     * If a new <tt>Integer</tt> 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.

     *

     * @param  i an <code>int</code> value.

     * @return a <tt>Integer</tt> instance representing <tt>i</tt>.

     * @since  1.5

     */

    public static Integer valueOf(int i) {

    final int offset = 128;

    if (i >= -128 && i <= 127) { // must cache 

        return IntegerCache.cache[i + offset];

    }

        return new Integer(i);

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值