Integer a = -128;
Integer b = -128;
//因为Integer缓存了[-128,127]的数据,赋值的时候直接返回缓存数据,不需要创建新的Integer对象
System.out.println(a == b); //true
System.out.println(a.equals(b)); //true
Integer c = 1234;
Integer d = 1234;
//1234不在缓存范围内,所以c,d是两个不同的对象,所以不同
System.out.println(c == d); //false
System.out.println(c.equals(d)); //true
学习笔记:Integer缓存[-128,127]之间的值
最新推荐文章于 2024-09-13 11:31:49 发布
本文探讨了Java中Integer对象的缓存机制,解释了在[-128,127]范围内Integer对象的比较为何会返回true,而超出此范围的对象比较则返回false,尽管它们的数值相等。通过示例代码展示了Integer对象在不同情况下的行为。
996

被折叠的 条评论
为什么被折叠?



