Integer和Int的比较,谈谈拆卸和装箱

示例代码

public static void main(String[] args) {
        Integer a = new Integer(10111);
        int b = 10111;
        boolean equal1 = a == b;//自动拆箱,xxxValue()
        boolean equal2 = a.equals(b);//自动装箱, valueOf()
        System.out.println(equal1);
        System.out.println(equal2);
}

反编译后

public static void main(String args[])
{
    Integer a = new Integer(10111);
    int b = 10111;
    boolean equal1 = a.intValue() == b; //自动拆箱
    boolean equal2 = a.equals(Integer.valueOf(b));//自动装箱
    System.out.println(equal1);
    System.out.println(equal2);        
}

区别

  1. Integer 是引用类型,int是基本类型
  2. Ingeter是int的包装类,内部封装持有一个int类型的值。int的初值为0,Ingeter的初值为null。
  3. Integer是引用类型,Integer间的比较必须用 equals()

拆箱

当 Integer a 与 int b 进行运算时,如:比较、加减等,会自动拆箱,即获取a持有的 int 值,然后再与 b 进行运算。

包装类型的拆箱通过 xxxValue() 方法实现,该方法直接返回包装的值。
xxx 代表基本数据类型,如:
Integer 的拆箱方法为 intValue()

public int intValue() {
        return value;
}

装箱

装箱通过valueOf() 实现,该方法可能会缓存部分值
如:Integer 默认会缓存 [-128, 127]的值,当通过 valueOf 创建一个 在[-128, 127]的 Integer 之后,会缓存该对象,再次创建该值的Integer会直接返回缓存中的对象,不会创建新对象

当 Integer a 和 int b,使用equals() 比较时,会自动装箱,将b封装成一个Integer

public static Integer valueOf(int i) {
		//默认情况下,i在[-128, 127]会直接返回缓存中的对象
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
}

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值