# 奇怪的Java题：为什么1000 == 1000返回为False，而100 == 100会返回为True?

492人阅读 评论(0)

Integer a = 1000, b = 1000;
System.out.println(a == b);//1
Integer c = 100, d = 100;
System.out.println(c == d);//2

false
true

Integer c = 100;

Integer i = Integer.valueOf(100);

static final int low = -128;
static final int high;
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;
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && ii <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

Integer c = 100, d = 100;

System.out.println(c == d);

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

Class cache = Integer.class.getDeclaredClasses()[0]; //1
Field myCache = cache.getDeclaredField("cache"); //2
myCache.setAccessible(true);//3

Integer[] newCache = (Integer[]) myCache.get(cache); //4
newCache[132] = newCache[133]; //5:这里将缓存值的[132]替换为[133]

int a = 2;
int b = a + a;
System.out.println(b);
System.out.printf("%d + %d = %d", a, a, b); //
}

0
0

个人资料
• 访问：176083次
• 积分：1669
• 等级：
• 排名：千里之外
• 原创：17篇
• 转载：26篇
• 译文：0篇
• 评论：11条
阅读排行
最新评论