包装器类型
自动拆箱与自动装箱
- 自动装箱是指将基本类型自动转换成对应的包装类类型
- 自动拆箱则是指将包装类自动转换成基本类型
例如:
Integer a = 1234; // 自动装箱
int b = a; // 自动拆箱
int c = 1234;
System.out.println(a == c); // true 也是自动拆箱的过程
128陷阱
我们观察这一段代码,发现输出是ttft
public class Main{
public static void main(String[] args){
Integer a = 120;
Integer b = 120;
int c = 120;
System.out.println(a == b);
System.out.println(a == c);
Integer x = 1234;
Integer y = 1234;
int w = 1234;
System.out.println(x == y);
System.out.println(x == w);
}
}
运行结果:
先给出结论,当Integer类型的数值在[-128,127]之间时,所有的都是同一个引用,而超出这个范围的就是两个不同的引用。
再给出原理:
我们从参考资料中找到这样一句话:装箱过程实际上是通过调用包装类的valueOf方法实现的。
即:
Integer a = 123;
等价于
Integer b = Integer.valueOf(123);
System.out.println(a == b);// true
我们就可以查看valueOf的源码:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
对这个源码的解释:当给定的参数在IntegerCache.low与IntegerCache.high之间时,我们就返回一个以及创建好的对象,否则就重新new一个对象。接着我们我们找到内部静态类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;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
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;
}
private IntegerCache() {}
}
我们观察源码发现,当数值范围在[-128,127]是,都是存在一个叫作cache的Integer数组中,并且创建好了数组的长度是256,也就是说我们已经new了256个对象,他们的值是从-128到127的,然后存储到cache数组中。
因此我们就得到一个结论:当Integer的范围在[-128,127]时,使用的时已经创建好的对象,是同一个对象,而超出这个范围的都是需要程序new一个对象,他们就是不同的对象,因此使用==时就会出现218陷阱。此时我们就可以使用equals来比较大小。