public class Main {
public static void main(String[] args) {
Integer num1 = 40;
Integer num2 = 40;
System.out.println(num1 == num2);
Integer num3 = 340;
Integer num4 = 340;
System.out.println(num3 == num4);
}
}
运行结果:
———————————————————————————————————————————
.class文件内容。
按道理说在使用Integer对象是,会进行自动装箱,调用Integer.valueOf(),创建一个Integer对象,怎么会出现==结果是true的情况呢?
这就要说到Integer内的缓存内容。下面是原码。
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 =
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会缓存-127-128,所以只要数字在这个区间就不会创建Integer对象。