首页 > 试题广场 >

"public class Test&nbs...

[单选题]
"public class Test {

    public static void main(String[] args) {
        Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;

        System.out.println(f1 == f2);
        System.out.println(f3 == f4);
    }
}"
  • true/false
  • true/true
  • fasle/ture
Integer 类型的会缓存-128~127 之间的数
private static class IntegerCache {
    static final int low = -128;
    static final int high;
    static final Integer ***[];
    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;
        *** = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < ***.length; k++)
            ***[k] = new Integer(j++);
        // range [-128, 127] must be interned (JLS7 5.1.7)
        assert IntegerCache.high >= 127;
    }
    private IntegerCache() {}
}

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.***[i + (-IntegerCache.low)];
    return new Integer(i);
}
发表于 2019-01-17 21:00:19 回复(0)
JVM会自动维护八种基本类型的常量池,int常量池中初始化-128~127的范围,所以当为Integer i=100时的属于128~127的范围内时,在自动装箱的过程中取的是常量池中的数值,而500不在次范围内,所以需要new因此地址不一样。
发表于 2018-12-16 20:40:01 回复(0)