为什么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);
复制代码

运行结果如下

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

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

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

所以我们在声明类似——

Integer c = 100;
的时候,它实际上在内部做的是——

Integer i = Integer.valueOf(100);

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

 1     /**
 2      * Returns an {@code Integer} instance representing the specified
 3      * {@code int} value.  If a new {@code Integer} instance is not
 4      * required, this method should generally be used in preference to
 5      * the constructor {@link #Integer(int)}, as this method is likely
 6      * to yield significantly better space and time performance by
 7      * 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      * @param  i an {@code int} value.
13      * @return an {@code Integer} instance representing {@code i}.
14      * @since  1.5
15      */
16     public static Integer valueOf(int i) {
17         if (i >= IntegerCache.low && i <= IntegerCache.high)
18             return IntegerCache.cache[i + (-IntegerCache.low)];
19         return new Integer(i);
20     }
复制代码

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

所以——

Integer c = 100,d = 100;
指向同一个对象,所以输出才会是true。

转载于:https://juejin.im/post/5bc6ea776fb9a05d1117b282

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值