一篇文章搞定系列:装箱和拆箱

本文参考:http://www.cnblogs.com/dolphin0520/p/3780005.html

装箱 int -》integer,integer ainteger =1;反编译后的实际上是Integer.valueOf(1)

拆箱 integer-〉int,int a = ainteger;反编译后实际上是ainteger.intValue();

规则:

1.== 两边的类型是包装类型,比较的是是否是同一个对象,比较的是地址。

2. == 有1边的数据是基本数据类型,比较的是数值、

3. a+b 等算数运算会触发拆箱操作

4.equals 会触发装箱操作

依据这些看例子

        Integer a = 1;
        Integer b = 2;
        Integer c = 3;
        Integer d = 3;
        Integer e = 321;
        Integer f = 321;
        Long g = 3L;
        Long h = 2L;
         
        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));
        System.out.println(g.equals(a+h));

需要注意一下的是倒数第二个结果是false。这里看下long的equlas源码可知,传过来的对象不是long类型的直接返回false,因此long.equals(integer)返回false。

 public boolean equals(Object obj) {
        if (obj instanceof Long) {
            return value == ((Long)obj).longValue();
        }
        return false;
    }

这些反编译后的代码为:

package com.my.java.base;

import java.io.PrintStream;



public class TestMZhuangChaiXiang
{
  public TestMZhuangChaiXiang() {}
  
  public static void main(String[] paramArrayOfString)
  {
    Integer localInteger1 = Integer.valueOf(1);
    Integer localInteger2 = Integer.valueOf(2);
    Integer localInteger3 = Integer.valueOf(3);
    Integer localInteger4 = Integer.valueOf(3);
    Integer localInteger5 = Integer.valueOf(321);
    Integer localInteger6 = Integer.valueOf(321);
    Long localLong1 = Long.valueOf(3L);
    Long localLong2 = Long.valueOf(2L);
    
    System.out.println(localInteger3 == localInteger4);
    System.out.println(localInteger5 == localInteger6);
    System.out.println(localInteger3.intValue() == localInteger1.intValue() + localInteger2.intValue());
    System.out.println(localInteger3.equals(Integer.valueOf(localInteger1.intValue() + localInteger2.intValue())));
    System.out.println(localLong1.longValue() == localInteger1.intValue() + localInteger2.intValue());
    System.out.println(localLong1.equals(Integer.valueOf(localInteger1.intValue() + localInteger2.intValue())));
    System.out.println(localLong1.equals(Long.valueOf(localInteger1.intValue() + localLong2.longValue())));
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值