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

这是一个挺有意思的讨论话题。

如果你运行下面的代码:

Integer a = 1000, b = 1000;  
System.out.println(a == b);//1
Integer c = 100, d = 100;  
System.out.println(c == d);//2

你会得到

false
true

基本知识:我们知道,如果两个引用指向同一个对象,用 == 表示它们是相等的。如果两个引用指向不同的对象,用 == 表示它们是不相等的,即使它们的内容相同。

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

这就是它有趣的地方了。如果你看去看 Integer.java 类,你会发现有一个内部私有类,IntegerCache.java,它缓存了从 - 128 到 127 之间的所有的整数对象。

所以事情就成了,所有的小整数在内部缓存,然后当我们声明类似——

Integer c = 100;

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

Integer i = Integer.valueOf(100);

而Integer类中的valueOf方法是这样的

/**
  * 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);
}

注释的大致意思是

返回表示指定int值的Integer实例。 如果不需要新的Integer实例,则通常应优先使用此方法而不是构造函数Integer(int) ,因为此方法通过缓存频繁请求的值可能会产生明显更好的空间和时间性能。 此方法将始终缓存 -128 到 127(含)范围内的值,并且可能缓存此范围之外的其他值

所以…当定义的值在-128到127之间时, 使用的是同一个对象. 所以 c==d的结果为 true

Integer c = 100, d = 100;
System.out.println(c == d);  // true

同样的 Long, Short 中也有缓存cache. 值也是 -128~127

例如在实体类中, 主键ID的类型为Integer, 在集合中需要去重. 则需要重写实体类中的equals和hashCode方法.这时候就不能使用 == 比较两个值是否相等, 而是使用equals(). 因为Integer中的equals方法会转为int类型. 源码如下

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
}

通过反射 API 你可能会误用此功能

运行下面的代码,享受它的魅力吧

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

      Class cache = Integer.class.getDeclaredClasses()[0]; 
      Field myCache = cache.getDeclaredField("cache"); 
      myCache.setAccessible(true);

      Integer[] newCache = (Integer[]) myCache.get(cache); 
      newCache[132] = newCache[133]; 

      int a = 2;
      int b = a + a;
      System.out.printf("%d + %d = %d", a, a, b); // 2 + 2 = 5 ?
}

注意System.out.printf()方法的参数类型

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明天你好369

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值