参考&鸣谢
JDK核心JAVA源码解析(8) - 自动封箱拆箱与效率的思考
[java]深度剖析自动装箱与拆箱
Java 为什么要有包装类
深入剖析Java中的装箱和拆箱
本文基于 Java 14
在JDK1.5引入自动装箱/拆箱,让开发更高效。自动装箱时编译器调用valueOf()将原始类型值转换成对象,同时自动拆箱时,编译器通过调用类似intValue(),doubleValue()这类的方法将对象转换成原始类型值。 自动装箱是将 float 值转换成 Float 对象,int 转换成 Integer,long 转换成 Long,short 转换成 Short等等,自动拆箱则是相反的操作。
| 基本数据类型 | 包装类 | 
|---|---|
| byte | Byte | 
| short | Short | 
| int | Integer | 
| long | Long | 
| float | Float | 
| double | Double | 
| char | Character | 
| boolean | Boolean | 
我们知道Java是一个面相对象的编程语言,基本类型并不具有对象的性质,为了让基本类型也具有对象的特征,就出现了包装类型(如我们在使用集合类型Collection时就一定要使用包装类型而非基本类型),它相当于将基本类型“包装起来”,使得它具有了对象的性质,并且为其添加了属性和方法,丰富了基本类型的操作。
另外,当需要往ArrayList,HashMap中放东西时,像int,double这种基本类型是放不进去的,因为容器都是装object的,这是就需要这些基本类型的包装器类了。
我们就以Interger类为例,下面看一段代码:
public class Main {public static void main(String[] args) {Integer i = 10;int n = i;}
}
 
反编译class文件之后得到如下内容:

从反编译得到的字节码内容可以看出,在装箱的时候自动调用的是Integer的valueOf(int)方法。而在拆箱的时候自动调用的是Integer的intValue方法。
其他的也类似,比如Double、Character,不相信的朋友可以自己手动尝试一下。
因此可以用一句话总结装箱和拆箱的实现过程:
装箱过程是通过调用包装器的valueOf方法实现的,而拆箱过程是通过调用包装器的 xxxValue方法实现的。(xxx代表对应的基本数据类型)。
自动装箱会根据基础数据类型的值创建对应的包装器类型对象。
实现方式
自动装箱机制是通过自动调用包装器类的valueOf()方法实现的,即Integer i = 1000,实际上执行的是Integer i = Integer.valueOf(1000)。
为了节省内存、提高性能,部分包装器类型缓存了值在[-128 — 127]区间内的对象。这些包装器类型包括Character、Byte、Short、 Integer和Long。下面以Integer类型为例说明。
Integer源码(Java 7)Integer valueOf(int i)函数实现如下
public static Integer valueOf(int i) { assert IntegerCache.high >= 127;if (i >= IntegerCache.low && i <= IntegerCache.high)return IntegerCache.cache[i + (-IntegerCache.low)];return new Integer(i);
}
 
默认情况下,缓存类IntegerCache的属性low和high的值分别为-128和127。可以看出,当整数值处于区间[-128, 127]中时,会之间从IntegerCache中获取对象,否则创建新对象。
静态类IntegerCache定义如下,在该类被加载时会执行静态代码块,读取缓存区间的右边界,并在对象数组cache中创建区间内的所有对象。因此从IntegerCache中获取的值相同的对象是同一对象。
private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[];static {// high value may be configured by propertyint h = 127; String integerCacheHighPropValue =sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");if (integerCacheHighPropValue != null) {int i = parseInt(integerCacheHighPropValue);i = Math.max(i, 127);// Maximum array size is Integer.MAX_VALUEh = Math.min(i, Integer.MAX_VALUE - (-low) -1); }    high = h;cache = new Integer[(high - low) + 1];int j = low;for(int k = 0; k < cache.length; k++)cache[k] = new Integer(j++);}private IntegerCache() {}
}
 
再看一下Boolean的实现
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);public static Boolean valueOf(boolean b) {return (b ? TRUE : FALSE);
}
 
其中TRUE和FLASE为静态常量,因此也可以理解为对true和false进行了缓存。
Character、Byte、Short、 Integer和Long类的valueOf()函数实现大致相同。但Float和Double类中valueOf()函数的实现只是直接创建一个对应的对象(如new Float(f)),因为某个区间内该类型的值的个数不是有限的。
注意,缓存策略只针对自动装箱的情形有效,而对于直接创建的包装器类型对象不会被缓存。
示例
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 200;
Integer i4 = 200;
System.out.println(i1 == i2);   // true
System.out.println(i3 == i4);   // falseDouble d1 = 100.0;
Double d2 = 100.0;
Double d3 = 200.0;
Double d4 = 200.0;
System.out.println(d1 == d2);   // false
System.out.println(d3 == d4);   // falseBoolean b1 = false;
Boolean b2 = false;
Boolean b3 = true;
Boolean b4 = true;
System.out.println(b1 == b2);   // true
System.out.println(b3 == b4);   // true
 
实际上针对有缓存的包装器类型,只需要判断对象的值是否在缓存区间内:值相等、值在缓存区间内、且通过自动装箱机制生成的两个变量是同一对象。
拆箱机制将包装器类型对象转化为对应的基础数据类型,当包装器类型变量遇到算数运算时会进行拆箱操作。
Integer integer = 100;   // 自动装箱
int i = integer;         // 拆箱
 
实现方式
拆箱机制是通过自动调用包装器类的xxxValue()方法实现。以Integer为例,Integer类有不可修改的属性value,存放对应的值。拆箱时会自动调用intValue()方法返回value值。
private final int value;public int intValue() {return value;
}
 
其他包装器类型的拆箱方式与Integer类似。可以看出,包装器类型的对象都是不可变的。
示例1
分析下面一段代码,这是在今天编写一个多线程程序时遇到的问题,最后发现不是线程同步的问题,而是自动装箱、拆箱机制的原因。简化如下
public class Test {public static Integer modify(Integer i) {i++;return i;}public static void main(String[] args) {Integer i = 200;System.out.println(i == modify(i));    // false}
}
 
i == modify(i)的比较结果是false,说明这两个对象不是同一对象。使用Java Decompiler反编译代码如下
import java.io.PrintStream;public class Test {public static Integer modify(Integer paramInteger) {Integer localInteger1 = paramInteger;Integer localInteger2 = paramInteger = Integer.valueOf(paramInteger.intValue() + 1);return paramInteger;}public static void main(String[] paramArrayOfString) {Integer localInteger = Integer.valueOf(200);System.out.println(localInteger == modify(localInteger));}
}复制代码
 
从modify()函数第二行代码可以看出,i++操作实际上进行了拆箱和装箱两步操作,然后把新对象又赋值给了原变量。因此输出结果为false。
示例2
分析下面一段代码
public class Test {public static void main(String[] args) {Integer i1 = 2;Integer i2 = 2;Integer i3 = i1 + i2;int i4 = i1 + i2;Long l1 = 4L;Long l2 = 0L;System.out.println(i1 == i2);                // trueSystem.out.println(i3 == i4);                // trueSystem.out.println(i3 == (i1 + i2));         // trueSystem.out.println(l1.equals(i1 + i2));      // falseSystem.out.println(l1.equals(i1 + i2 + l2)); // true}
}
 
反编译结果如下
public class Test {public static void main(String[] paramArrayOfString) {Integer localInteger1 = Integer.valueOf(2);Integer localInteger2 = Integer.valueOf(2);Integer localInteger3 = Integer.valueOf(localInteger1.intValue() + localInteger2.intValue());int i = localInteger1.intValue() + localInteger2.intValue();Long localLong1 = Long.valueOf(4L);Long localLong2 = Long.valueOf(0L);System.out.println(localInteger1 == localInteger2);System.out.println(localInteger3.intValue() == i);System.out.println(localInteger3.intValue() == localInteger1.intValue() + localInteger2.intValue());System.out.println(localLong1.equals(Integer.valueOf(localInteger1.intValue() + localInteger2.intValue())));System.out.println(localLong1.equals(Long.valueOf(localInteger1.intValue() + localInteger2.intValue() + localLong2.longValue())));}
}
 
通过该示例可分析出
==或equals比较)才会自动装箱Integer与int等值比较时判断的是数值是否相等Integer对象间的大小比较(>、<)是比较数值大小,等值比较(==)是测试是否是同一对象微回顾
什么是装箱、拆箱?
在JDK1.5引入自动装箱/拆箱,让开发更高效。自动装箱时编译器调用
valueOf()将原始类型值转换成对象,同时自动拆箱时,编译器通过调用类似intValue(),doubleValue()这类的方法将对象转换成原始类型值。为什么会引入?
我们知道Java是一个面相对象的编程语言,基本类型并不具有对象的性质,为了让基本类型也具有对象的特征,就出现了包装类型。
它相当于将基本类型“包装起来”,使得它具有了对象的性质,并且为其添加了属性和方法,丰富了基本类型的操作。