10 100 1000java,谈一谈Java 中 1000==1000 为false,而100==100 为true?

JDK在1.5版本中添加的一项新特性,会把-128~127的数字缓存起来,用于提升性能和节省内存。

运行单元测试代码如下:

@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

}

}

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

441d22d0ad100fa3a505366d1322cb88.png

原因是 在这里声明 的 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

本文同步分享在 博客“早起的年轻人”(CSDN)。

如有侵权,请联系 support@oschina.cn 删除。

本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值