java自动装箱,自动拆箱

什么是自动装箱和拆箱

很简单,下面两句代码就可以看到装箱和拆箱过程

//自动装箱
 Integer total = 99;
 
 //自定拆箱
 int totalprim = total;
  • 装箱就是自动将基本数据类型转换为包装器类型;
  • 拆箱就是自动将包装器类型转换为基本数据类型。

下面我们来看看需要装箱拆箱的类型有哪些:
自动装箱/拆箱包装类


自动装箱

源码:

public static Integer valueOf(int i) {
     if (i >= IntegerCache.low && i <= IntegerCache.high)
         return IntegerCache.cache[i + (-IntegerCache.low)];
     return new Integer(i);
 }

其中:

static final int low = -128;
static final int high= 127;
static final Integer cache[] = new Integer[(high - low) + 1];

分析:

  1. Integer total = 99; 调用valueOf(int i)方法
  2. 如果 i 小于 -128 或者 i 大于127,就new Integer(i)
  3. 如果 i 大于 -128 并且 i 小于 127 ,就调用缓存区提前创建好的对象

案例

       Integer a1 = 89;
       Integer a2 = 89;
       System.out.println(a1 == a2); // true

       Integer b1 = 130;
       Integer b2 = 130;
       System.out.println(b1 == b2); // false

进行归类:

Integer派别:Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。
Double派别:Double、Float的valueOf方法的实现是类似的。每次都返回不同的对象。

类型相同值范围不同值范围
Integer(-128,128)i >= 128 或者 i < -128
Short(-128,128)s >= 128 或者 s < -128
Characterc<128c >= 128
Long(-128,128)l >= 128 或者 l < - 128
Boolean b1 = true;
Boolean b2 = true;
System.out.println(b1 == b2); //true
public static Boolean valueOf(boolean b) {
    return b ? Boolean.TRUE : Boolean.FALSE;
}

分析:
可以看到它并没有创建对象,因为在内部已经提前创建好两个对象,因为它只有两种情况,这样也是为了避免重复创建太多的对象。


自动拆箱

源码:

private final int value;

public int intValue() {
    return value;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值