为什么 Java 中“1000==1000”为false,而”100==100“为true?
阅读本文大概需要 2 分钟。
来自: 码农网
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);
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i
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
int a = 2;
int b = a + a;
System.out.printf("%d + %d = %d", a, a, b); //
}
推荐阅读:
微信扫描二维码,关注我的公众号
朕已阅
评论