天天看点

java自动装箱,自动拆箱什么是自动装箱和拆箱自动装箱自动拆箱

文章目录

  • 什么是自动装箱和拆箱
  • 自动装箱
    • 源码:
      • 案例
      • 进行归类:
  • 自动拆箱
    • 源码:

什么是自动装箱和拆箱

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

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

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

java自动装箱,自动拆箱什么是自动装箱和拆箱自动装箱自动拆箱

自动装箱

源码:

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
Character c<128 c >= 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;
}