为什么 Java 中 1000==1000 为 false ?
公众号程序猿DD
共 1722字,需浏览 4分钟
·
2020-09-16 23:27
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); //
}
往期推荐
最后,推荐一个专注分享后端面试要点的公众号「后端面试那些事儿」,置顶标星。每日一篇常问的面试问题,秀的一批~扫描下方二维码关注!
评论