首页 文章详情

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

全栈架构社区 | 197 2021-10-28 23:13 0 0 0
UniSMS (合一短信)
相关阅读

300本计算机编程的经典书籍下载

AI全套:Python3+TensorFlow打造人脸识别智能小程序

最新人工智能资料-Google工程师亲授 Tensorflow-入门到进阶

Java架构全阶段七期完整

黑马头条项目 - Java Springboot2.0(视频、资料、代码和讲义)14天完整版

Spring核心编程思想


如果你运行下面的代码:
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()方法的参数类型

作者:明天丶你好_3f99
链接:https://www.jianshu.com/p/95b7b4b3af20


全栈架构社区交流群

 「全栈架构社区」建立了读者架构师交流群,大家可以添加小编微信进行加群。欢迎有想法、乐于分享的朋友们一起交流学习。

扫描添加好友邀你进架构师群,加我时注明姓名+公司+职位】

看完本文有收获?请转发分享给更多人


往期资源:


Flutter 移动应用开发实战 视频(开发你自己的抖音APP)
Java面试进阶训练营 第2季(分布式篇)
Java高级 - 分布式系统开发技术视频


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter