Java中判等陷阱的理解

一般来讲,java中判断基本数据类型是否相等用==,而对象的判等则使用equals方法。

如果对于两个不同的对象使用==进行判等,这时候判断的两个对象的引用是否相等,那么返回值应该是false。可是下面这段代码的执行结果就让人有点费解了

		Integer i1 = 100;
		Integer i2 = 100;
		Integer i3 = new Integer(100);
		Integer i4 = new Integer(100);
		System.out.println(i1 == i2);
		System.out.println(i3 == i4);

执行结果如下:

true

false

按照通常思维,i1 和 i2应该属于不同的对象,那么 i1==i2应该返回false,可是这里为什么是true呢?

这里就要说到java中的自动装箱了,上面例子中,当执行 Integer i1 = 100 的时候,实际上是执行了 Integer i1 = Integer.valueOf(100)。

下面是Integer类的 valueOf(int) 方法:

public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)  
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
当 i 的值在 IntegerCache.low 和 IntegerCache.high之间时,返回的是 IntegerCache对象中 cache数组中存放的Integer对象,否则创建一个新的Integer对象。

我们继续看IntegerCache的源码:

 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) {
                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);
            }
            high = h;

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

        private IntegerCache() {}
    }
low的值为-128 ,high的值默认为127。

现在就很容易解释示例的结果了:i1 和 i2 的值在-128 ~ 127范围内,那么返回的是IntegerCache中的Integer对象,i1和i2实际上引用的是同一个对象,故 i1 == i2为 true,而 i3和i4指向不同对象,故i3 == i4 为false。 

另外Character < 127, -128 < Short < 127 ,-128 < Byte < 127, -128 < Long < 127 都会出现类似的情况。






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值