您的位置:首页 > 编程语言 > Java开发

Java中Integer的变量比较源码解析

2015-09-01 15:28 411 查看

面试例子:

[code]public static void main(String arg[]){  
     Integer a=3;  
     Integer b=3;  
     System.out.println(a==b);  
     System.out.println(a.equals(b));  
     a=3333;  
     b=3333;  
     System.out.println(a==b);  
     System.out.println(a.equals(b));  

 }


此程序打印出来的结果分别为:true,true,false,true。那么为什么会出现这种结果呢?

原因分析

我们要知道当给一个Integer对象赋一个int值时,Integer的valueOf方法会被调用。那么,我们看看Integer的valueOf方法到底做了些什么。源码如下:

代码一:

[code]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);
}


代码二:

[code]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() {}
}


通过代码一我们可以看出,当valueOf传入的值在IntegerCache.low和IntegerCache.high之间时,Integer被赋的值将从IntegerCache.cache数组中获得,也就是通过缓存中获得。

再看代码二,IntegerCache.low为常量-128。而IntegerCache.high如果在启动JVM时没有指定-XX:AutoBoxCacheMax参数,默认为127。综合两段代码,我们可以知道,在默认情况下,在-128到127之间的数据在赋值时会从缓存中获得。

结论

因此,在-128到127之间的数据多次获得的均为同一个对象,而超出这个范围的数据将会创建一个新的对象,只能通过equals方法比较的才是对象的值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: