您的位置 首页 java

谈一谈Java中100==100为true?

谈一谈Java中100==100为true?

运行单元测试代码如下:

 @SpringBootTest
class DemoApplicationTests {
  @Test
  void test() {

    Integer a = 10000, b = 10000;
    System.out.println(a == b);// false

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

}
  

然后输出结果如下图所示:

谈一谈Java中100==100为true?

原因是 在这里声明 的 a、b、c、d 四个变量为 Integer 对象 ,使用 == 比较的是 变量指向的对象内容地址,或者说 使用 == 号比较的是 Integer 对象的 hash 值 。

那么 a、b、c、d 应该是四个不同的对象,对应的指针hash 值也应当不一样,而在这里 c与d的却是一样了。

这是因为在 Integer.java 类中有一个私有内部类 IntegerCache.java,它用来缓存取值范围在 -128到127 之间的所有的整数对象,如果值的范围在-128到127之间,它就从高速缓存返回实例,如果不在,则创建新的 Integer 对象, 这就是 上述 变量 a 与 b 比较结果为 false ,而变量 c 与 d 的比较结果 为true 的原因。


如下 Integer 的 valueOf 方法构建 Integer 实例的源码:

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

如在职场面试中会有如下的题:

 public class Test {
    public static void main(String[] args) {
        Integer int1 = Integer.valueOf("100");
        Integer int2 = Integer.valueOf("100");
        System.out.println(int1 == int2);
    }
}
  

毫无疑问最后的输出结果是 true

文章来源:智云一二三科技

文章标题:谈一谈Java中100==100为true?

文章地址:https://www.zhihuclub.com/197347.shtml

关于作者: 智云科技

热门文章

网站地图