为什么 Java 中“1000==1000”为false,而”100==100“为true?
点击上方“码农突围”,马上关注
这里是码农充电第一站,回复“666”,获取一份专属大礼包
真爱,请设置“星标”或点个“在看”

英文原文:https://dzone.com/articles/why-1000-1000-returns-false-but-100-100-returns-tr
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); //
}
最近热文
• 太优秀了!26岁当上985博导,这才是乘风破浪的姐姐! • fastjson的作者,在阿里内网被喷,这到底是怎么一回事? • 为什么有些大公司技术弱爆了? • 微软最新声明:若断供中国Windows,概不负责! 最近整理了一份大厂算法刷题指南,包括一些刷题技巧,在知乎上已经有上万赞。同时还整理了一份6000页面试笔记。关注下面公众号,在公众号内回复「刷题」,即可免费获取!回复「加群」,可以邀请你加入读者群!
明天见(。・ω・。)ノ♡
评论
