10 100 1000java,为什么Java中1000==1000为false而100==100为true

我们首先看下面一段代码

Integer a = 1000,b=1000;

System.out.println(a==b);

Integer c= 100,d = 100;

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

运行结果如下

20181006100708283259.png

按照我们的理解,如果两个引用指向同一个对象,用==表示它们是相等的。如果两个引用指向不同的对象,==代表不相等的,即使它们的内容相同。

因此,后面一条语句应该也是false。

分析:

我们看下Integer.java类,我们会发现有一个内部私有类,IntegerCache.java,它缓存了从-128~127之间的所有的整数对象。

所以我们在声明类似——

Integer c = 100;

的时候,它实际上在内部做的是——

Integer i = Integer.valueOf(100);

我们看下valueOf()方法,可以看到

1 /**

2 * Returns an {@codeInteger} instance representing the specified3 * {@codeint} value. If a new {@codeInteger} instance is not4 * required, this method should generally be used in preference to5 * the constructor {@link#Integer(int)}, as this method is likely6 * to yield significantly better space and time performance by7 * caching frequently requested values.8 *9 * This method will always cache values in the range -128 to 127,10 * inclusive, and may cache other values outside of this range.11 *12 *@parami an {@codeint} value.13 *@returnan {@codeInteger} instance representing {@codei}.14 *@since1.515 */

16 public static Integer valueOf(inti) {17 if (i >= IntegerCache.low && i <=IntegerCache.high)18 return IntegerCache.cache[i + (-IntegerCache.low)];19 return newInteger(i);20 }

如果值的范围在-128~127之间,它就从高速缓存返回实例。

所以——

Integer c = 100,d = 100;

指向同一个对象,所以输出才会是true。

原文:https://www.cnblogs.com/NullCXY/p/9746495.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值