- 自动装箱和自动拆箱
把基本类型转换成包装类型的过程叫做装箱(Integer.valueOf() )。
反之,把包装类型转换成基本类型的过程叫做拆箱(Integer.intValue())。
Integer num1 = 10; // 自动装箱 Integer num1 = Integer.valueOf(10);
int num2 = num1; // 自动拆箱 int num2 = num1.intValue();
- 用 "=="比较
基本类型和包装类型进行 == 比较,这时候包装类型会自动拆箱,直接比较值,所以结果为 true。
当需要进行自动装箱时,如果数字在 -128 至 127 之间时,会直接使用缓存中的对象,而不是重新创建一个对象。
// 1)常量池,在-128~127的范围内,被缓存在常量池中
Integer num1 = new Integer(100);//堆
Integer num2 = new Integer(100);//堆
int num3 = 100;//常量池
int num4 = 100;//常量池
Integer num5 = 100;//常量池,
Integer num6 = 100;//
System.out.println(num1 == num2);//false
System.out.println(num2 == num3);//true 自动拆箱
System.out.println(num2 == num5);//false
System.out.println(num3 == num4);//true
System.out.println(num3 == num5);//true 自动拆箱
System.out.println(num5 == num6);//true 常量池,在-128~127的范围内,被缓存在常量池中
//2)堆,超出-128~127的范围,不被缓存
num1 = new Integer(200);//堆
num2 = new Integer(200);//堆
num3 = 200;
num4 = 200;
num5 = 200;
num6 = 200;
System.out.println(num1 == num2);//false
System.out.println(num2 == num3);//true 自动拆箱
System.out.println(num2 == num5);//false
System.out.println(num3 == num4);//true
System.out.println(num3 == num5);//true 自动拆箱
System.out.println(num5 == num6);//false 堆,超出-128~127的范围,不被缓存
- 自动装箱源码
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
- 关键类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 property
int h = 127;
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
h = 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++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
}