为什么Java中1000==1000为false而100==100为true

Integer有一个好玩的特性。如果你运行下面的代码:

public class test {
	public static void main(String[] args) {
		Integer a = 1000, b = 1000;
		Integer c = 100, d = 100;
		System.out.println("a==b:" + (a == b));
		System.out.println("c==d:" + (c == d));
	}
}
就会得到:
a==b:false
c==d:true

基础知识:如果两个引用指向同一个对象,用==表示它们是相同的,如果两个引用指向不同对象,用==则表示不相等的,即使它们的内容相同。因此,c==d,也应该为false。

但是,这就是Integer有趣的地方了。如果你去查看它的源码,就会发现在内部有一个私有类IntegerCache.java,它缓存了-128~127之间所有的整数对象,即在这之间的整数全部在内部缓存,而当我们声明:

Integer c = 100:
它其实在内部是这样的:
 /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
如果值在-128~127之间,它就会从高速缓存中返回实例:
Integer c = 100, d = 100;
所以它们指向了同一个对象。因此我们可以得到下面的结果:
c==d:true
现在你也许会问:为什么这里需要缓存?

在此范围内的小整数使用率比大整数要高,因此,使用相同的底层对象是有价值的,可以减少潜在的内存占用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值