Integer类型是基本类型int的包装类,能否直接用“==”判断相等呢? 废话不多说,上代码……
@Test
public void test11()throws Exception{
Integer a = 100;
Integer b = 100;
Integer c = Integer.valueOf(100);
System.out.println(a == b);//print: true
System.out.println(b == c);//print: true
}
嗯~,貌似是可以的呢…… 但是……
@Test
public void test12()throws Exception{
Integer a = 200;
Integer b = 200;
Integer c = Integer.valueOf(200);
System.out.println(a == b);//print: false
System.out.println(b == c);//print: false
}
哦豁~,为啥又不相等了呢? 这是因为在Integer类中,存在 256 个Integer 的缓存对象,封装 -128 到 127范围的数值,如果指定范围内的值,访问缓存对象,如果指定范围外的值,直接新建对象。 看源码~
内部缓存类:
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 = 127;
}
private IntegerCache() {}
}
valueOf()方法:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i |