在很多情况下,容易有一种假象,即基本类型与他们的对象包装器是一样的,只是他们的相等性不同。当使用==比较对象时,只不过检测他们是否指向同一个储存区域。因此,下面的比较通常不会成立:
然而,在Java中,它们可能是成立的。因为Java中,对于一些数据类型的“常用数值”采用了缓存策略。
就是在调用valueOf的时候,如果这个数值在cache数组的范围内,就返回cache数组的中的数据,否则产生一个新的Integer值。
<span style="font-size:18px;">Integer a=1000;
Integer b=1000;
return a==b;</span>
然而,在Java中,它们可能是成立的。因为Java中,对于一些数据类型的“常用数值”采用了缓存策略。
下面来看看Integer的缓存策略
在Integer类中,定义了一个私有的静态类,这个类是用来支持Integer缓存的,它的作用是把一部分Integer类型的数据在类加载的时候放在一个cache数组中,以便以后使用。通常这个范围是-128-127,然而这个范围的最大值是可变的,可以通过-XX:AutoBoxCacheMax=<size>参数去修改这个值,在JVM初始化的时候,这个值被写入sun.misc.VM class系统私有配置文件中,并加载
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() {}
}
在Integer类被加载以后,就已经存在这样一个cache数组,那它是如何被应用的呢?
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
就是在调用valueOf的时候,如果这个数值在cache数组的范围内,就返回cache数组的中的数据,否则产生一个新的Integer值。
这样就可以解释以下的现象了:
(1) 比较1000的时候返回false
Integer a=1000;
Integer b=1000;
System.out.println(a==b);
(2) 比较100的时候返回true
Integer a=100;
Integer b=100;
System.out.println(a==b);