面试题:Integer中非常重要的面试题,你不会还不知道吧

    技术2022-07-11  79

    分析一下代码:    1、为什么第一个输出为false,第二个输出为true?

    public static void main(String[] args) { Integer a = 128; Integer b = 128; System.out.println(a == b); // false Integer x = 127; Integer y = 127; System.out.println(x == y); // true }

    2、解释:

    Java中为了提高程序的执行效率,将 [-128,127]之间所有的包装类提前创建好,放到了一个方法区的"整数型常量池",目的:是只要用这个区间的数据不需要在new了,直接从“整数型常量池”中取出来。原理:x变量保存的对象的内存地址跟y中的一样都是指向方法区的"整数型常量池",所以第二个输出为true,又因为128在区间 [-128,127]之外,a、b两个引用指向的堆内存中的内存地址不同,所以第一个输出为false。

    3、Integer中的源码:

    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; }
    Processed: 0.009, SQL: 9