一个关于Integer的秘密

先让大家看一段简单的代码:

public static voidmain(String[] args) {
Integera = 1;
Integerb = 1;
 
Integerc = 222;
Integerd = 222;
 
System.out.println(a== b);
System.out.println(c== d);
}

大家猜一下,输出的结果会是什么?我想大多数初学者都会认为是:true  true。可是,实际呢?正确答案是:true

false。这时,是不是有人开始纳闷了,不禁问道:为什么呢?逻辑都一样,只是数字不同,难道跟数字有关?恭喜你,答对了,确实跟数字有关。下面我就带大家看看其中的缘由。

 

我们看一下integer源码中的两个方法:

publicstatic Integer valueOf(int i) {
        if(i >= -128 && i <=IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
    }
 
privatestatic class IntegerCache {
        static final int high;
        static final Integer cache[];
 
        static {
            final int low = -128;
 
            // high value may be configured byproperty
            int h = 127;
            if (integerCacheHighPropValue !=null) {
                // Use Long.decode here toavoid invoking methods that
                // require Integer's autoboxingcache to be initialized
                int i =Long.decode(integerCacheHighPropValue).intValue();
                i = Math.max(i, 127);
                // Maximum array size isInteger.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类型的变量时,如:Integer a = 1,实际上它调用了integer中的valueOf方法,相当于Integera = Integer.valueOf(1),而在这个方法内部有一个缓存的机制。它会判断你给变量赋的值是否在-128——127之间,如果是,那么它直接从缓存里去取对象,反之才会新创建一个对象。

也就是说,当程序执行Integerb = 1时,缓存中已经存在这个integer对象,它直接将b指向缓存中的对象,结果就是ab指向同一对象,而cd就不同了,它们两个最终会指向两个新创建的不同的对象,执行c==d时,自然不会相等。现在大家该明白了吧。

 

明白了这个原理,最重要的还是要应用于实际,当我们在程序中操作小整型数字的时候,我们要充分利用integer中的缓存机制,节省程序创建对象的时间,以此来提高我们程序的效率。

 

最后,如果有人关心==equal的区别,请看下面这篇文章:

详解java中equals和== 的区别



 

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值