含义
装箱 自动将基本数据类型转换为包装器类型;
拆箱: 自动将包装器类型转换为基本数据类型
以Integer为例
//在栈中创建了两个对象
int a1 = 1;
int a2 = 1;
//在栈中创建了两个引用,1个对象,存储在栈中,发生了自动装箱
Integer oa1 = 2;//装箱
Integer oa2 = 2;//装箱
//栈中创建了一个3对象,堆中创建了一个Integer对象,一个引用
int a3 = 3;
Integer oa3 = new Integer(3);
//栈中创建了一个255对象,一个引用
int a4 = 127;
Integer oa4 = 127;//装箱
//栈中创建了一个256对象,一个引用,堆中创建了一个256对象
int a5 = 128;
Integer oa5 = 128;//超出[-128-127]不能自动装箱
使用 javap.exe -c basic.IntDemo 查看字节码指令
Code:
0: iconst_1
1: istore_0
2: iconst_1
3: istore_1
4: iconst_2
5: invokestatic #3 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
8: astore_2
9: iconst_2
10: invokestatic #3 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
13: astore_3
14: iconst_3
15: istore 4
17: new #4 // class java/lang/Integer
20: dup
21: iconst_3
22: invokespecial #5 // Method java/lang/Integer."<init>":(I)V
25: astore 5
27: bipush 127
29: istore 6
31: bipush 127
33: invokestatic #3 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
36: astore 7
38: sipush 128
41: istore 8
43: sipush 128
46: invokestatic #3 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
49: astore 9
51: return
发现 Integer.valueOf 这个方法被多次调用,直接上源码
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);
}
Integer 类是通过内部的一个IntegerCache 缓存了-128 - 127 的字面量,所以在此范围的int 不用new对象装箱,而是直接返回。