Java Integer 比较

本文深入探讨了Java中Integer缓存机制的工作原理,并通过一个简单的示例代码展示了当Integer对象值位于-128到127之间时,如何通过缓存来复用对象,从而提高程序性能。

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

 

public class Test {  
  
    public static void main(String[] args) {  
        int a = 1;  
        int b = 1;  
        Integer c = 3;  
        Integer d = 3;  
        Integer e = 321;  
        Integer f = 321;  
  
        System.out.println(a == b);  
        System.out.println(c == d);  
        System.out.println(e == f);  
  
    }  
}  
output:  
true  
true  
false  

 看到这个结果,一定非常的奇怪,为什么会出现这种情况。

 

原因就在Integer的方法 valueOf()方法。

public static Integer valueOf(int i) {  
        if(i >= -128 && i <= IntegerCache.high)  
            return IntegerCache.cache[i + 128];  
        else  
            return new Integer(i);  
    }  
  
private static class IntegerCache {  
        static final int high;  
        static final Integer cache[];  
  
        static {  
            final int low = -128;  
  
            // high value may be configured by property  
            int h = 127;  
            if (integerCacheHighPropValue != null) {  
                // Use Long.decode here to avoid invoking methods that  
                // require Integer's autoboxing cache to be initialized  
                int i = Long.decode(integerCacheHighPropValue).intValue();  
                i = Math.max(i, 127);  
                // Maximum array size is Integer.MAX_VALUE  
                h = Math.min(i, Integer.MAX_VALUE - -low);  
            }  
            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() {}  
    }  

 Integer里弄了一个缓存,对于在 -128—127 之间的数值,会直接使用该缓存里的对象  

 也就是说 Integer c = 3 或者 Integer c = Integer.valueOf(3) ,最终 c 得到的是Integer里的缓存对象  

 同理,d也是获得该相同对象因此 进行 c == d 比较时,c和d引用的是同一个对象,因此就true  

 而对于321,已经超出缓存范围了,因此 valueOf 方法会生成一个新的Integer对象因此e和f就引用不同 的对象了,进行==比较,当然就false了  

 另外,对Integer的缓存,我们在日常开发时,对于小的整型值应该充分利用Integer的缓存对象省去过多的对象创建,回收的操作,这样会极大的提高程序性能  。

所以如果想比较连个Integer 对象的值是否相等,可以equals()或者compareTo(),或者intValue()去比较。

参考文章:http://blog.youkuaiyun.com/zhoumingp/article/details/8298566

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值