128陷阱:
首先测试一段代码:
public static void main(String[] args) {
Integer num1 = 127;
Integer num2 = 127;
System.out.println(num1 == num2);
Integer num3 = 128;
Integer num4 = 128;
System.out.println(num3 == num4);
}
结果如下:
那么,上述答案出现的原因是什么呢?在解析之前,我们先来了解两个概念:
装箱:
把基本类型数据转成对应的包装类对象。
方式一:
Integer i = Integer.valueOf(13);
方式二:
Integer i = new Integer(13);
拆箱:
把包装类对象转成对应的基本数据类型数据。
int value = i.intValue();
在Java 5之前的版本中,基本数据类型和包装类之间的转换是需要手动进行的,但Sun公司从Java5开始提供了的自动装箱(Autoboxing)和自动拆箱(AutoUnboxing)操作 ;这个操作是由java编译器完成的(javac)。
所以,上述代码也可以写成:
public static void main(String[] args) {
Integer num1 = Integer.valueOf(127);
Integer num2 = Integer.valueOf(127);
System.out.println(num1 == num2);
Integer num3 = Integer.valueOf(128);
Integer num4 = Integer.valueOf(128);
System.out.println(num3 == num4);
}
上述问题的答案就呼之欲出了:
就在Integer的valueOf()方法当中,如果我们的数值在-128-127之间的数值都存储在有一个catch数组当中,该数组相当于一个缓存,当我们在-128-127之间进行自动装箱的时候,我们就直接返回该值在内存当中的地址,所以在-128-127之间的数值用==进行比较是相等的。而不在这个区间的数,需要新开辟一个内存空间,所以不相等。
用堆和栈概念来理解,如下图:
到此,128陷阱的原因也就解释清楚了,那为什么是-128-127呢?
让我们来看一下Integer的valueOf()的源码加深一下理解:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
由以上代码不难看出:
当 i >= IntegerCache.low && i <= IntegerCache.high时,返回一个已经存在于指定数组中的对象,而当其超出范围的时候,则新建一个对象。
而Java中两个用双等号比较对象时,比较的是它的地址。所以当i超出范围时,用双等号比较两对象,实际上是比较两个具有相同值的不同对象,结果当然不等。
那IntegerCache.low和IntegerCache.high 又是什么呢?
让我们进入IntegerCache看一下:
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer[] cache;
static Integer[] archivedCache;
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
h = Math.max(parseInt(integerCacheHighPropValue), 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
// Load IntegerCache.archivedCache from archive, if possible
VM.initializeFromArchive(IntegerCache.class);
int size = (high - low) + 1;
// Use the archived cache if it exists and is large enough
if (archivedCache == null || size > archivedCache.length) {
Integer[] c = new Integer[size];
int j = low;
for(int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}
archivedCache = c;
}
cache = archivedCache;
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
Javadoc 详细的说明这个类是用来实现缓存支持,并支持 -128 到 127 之间的自动装箱过程。
总结
-------------------------------------------------------------------------------------------------------------------------------
在基本类型的包装类运用时,还是更推荐大家使用equals方法来比较,因为这个方法比较的两个变量存在堆中的值是否相等。
而Java中两个用双等号比较对象时,比较的是它的地址。