有意思的面试题

173 阅读2分钟

1. IntergerCache

        Integer a = 100;//此处若使用new,则==值必为false
        Integer b = 100;
        System.out.println(a==b);//true
        Integer c = 150;
        Integer d = 150;
        System.out.println(c==d);//false

这里比较奇怪了,为什么前者是相等的,而后者不想等? 我们来分析一下:
首先,Integer a = 100 在编译时有个装箱的过程,即 Integer a = Integer.valueof(100) ,然后我们看看源码

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

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

可以看到,在调用valueof方法时,会先看看值是否在 -128 到 127之间,如果是127之间,会直接从 IntegerCache 中取,这里面的值是在一开始就开辟好内存区的。所以这里a和b地址是相同的,然后 == 对于引用类型来说比较的是引用,所以这里是相等的。而不在这个范围内的c和d,每次都是开辟新的空间,所以这里必然是不想等的。
好,接着往下看。

 public static void main(String []args) {
        Integer a = 100;//此处若使用new,则==值必为false
        Integer b = 100;
        a++;
        System.out.println(a==b);//false
        Integer c = 111;
        Integer d = 112;
        c++;
        System.out.println(c==d);//true
    }

看到上述代码运行的结果,可能就更加纳闷了, 首先 第一个 ,a++之后和b比较为false,原因在于 ++之后 a已经变成了 101的内存地址了,所以不相等。然后c和d 就比较好理解了,c在自加之后,地址变成了 缓存内112的地址。

综上 java在为了提高性能的时候,使用IntegerCache将 -128 到 127的值缓存至内存中,所以导致了 代码所出现的情况。