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

本文解析了Java中Integer对象在[-128,127]范围内使用缓存的机制,解释了为什么在这个范围内的Integer对象可以直接通过引用比较,而超出此范围的对象则需要使用equals方法来比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我在知乎上看到这个问题以及这个问题的解析,于是上网查了资料以及去java查看源码,做了以下简单的解析。

public static void test1() {

Integer a = 1; // 等价于 Integer a = valueOf(1)
Integer b = 1;
System.out.println(a == b); // true

Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false

System.out.println(c.equals(d)); // true
}

对于以上的结果,首先查看java帮助手册中,对Interger的valueOf(int i)是这么描述的:
这里写图片描述
理解上就是这样:在一定的范围[-128,127]中,对Integer的赋值操作(整形赋值)是直接通过调用valueOf(int i)的方法的。而接下来看看valueOf(int i),这里讲到了如果在大于low小于high的范围中,会直接使用cache中已经创建的实例,而超出这个范围的才会重新创建新的实例:

public static Integer valueOf(int i) {
      if (i >= IntegerCache.low && i
          return IntegerCache.cache[i + (-IntegerCache.low)];
      return new Integer(i);
    }

这里涉及到了IntegerCache.class这个类:

private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        String integerCacheHighPropValue =
            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
        if (integerCacheHighPropValue != null) {
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            } catch( NumberFormatException nfe) {
                // If the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);

        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }

因此,进行Integer对象相等性比较的时候,不能直接使用 == (比较的是对象的hashcode,只有[low,high]之间的Integer是相同的), 而应该使用equals方法。

英文原文:
https://dzone.com/articles/why-1000-1000-returns-false-but-100-100-returns-tr
译文链接:
http://www.codeceo.com/article/why-java-1000-100.html
文章的知乎专栏:
https://zhuanlan.zhihu.com/p/25421272
Interger文章:
http://www.importnew.com/18884.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值