Integer细节注意

问题引入
public class Demo{
    public static void main(String[] args){
        Integer i1 = 127;
        Integer i2 = 127;
        System.out.println(i1 == i2);//true
        String i3 = "100";
        String i4 = "1" + new String("00");
        System.out.println(i3 == i4);//false
        Integer i5 = 150;
        Integer i6 = 150;
        System.out.println(i5 == i6);//false
    }
}

解释

其实当我们给一个 Integer 赋一个int类型的值时有一个自动装箱的过程,用到了valueOf()方法

Integer f1 = Integer.valueOf(100);

valueOf()方法的源码如下

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


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;
        }

        private IntegerCache() {}
    }

从上面的源码我们可以看出,一个Integer对象的值的范围是 -128~127,如果在这个范围内,直接从cache中获取,这些cache引用对Integer对象地址是不变的,但是不在这个范围内的数字,则new Integer(i) 创建新的对,这个地址是新的地址

猜你喜欢

转载自blog.csdn.net/king123456man/article/details/81740111
今日推荐