Integer对象隐藏的面试题

来源:互联网 发布:sql 如何加一行合计 编辑:程序博客网 时间:2024/05/03 01:31

Integer对象隐藏的面试题
之前去一家公司面试,对方甩出一堆笔试题,其中有一道如下

        Integer a = 10;        Integer b = 10;        System.out.println(a == b);        Integer c = 128;        Integer d = 128;        System.out.println(c == d );

问你结果是神马,以我行走江湖多年经验(啊呸),这里面一定有坑,是套路,就算我侥幸猜对了,那帮老鸟也一定会在面试时再考我为什么。
本着知之为知之,不知为不知的精神,直接空在了那里,现在重新看了源码,才稍稍理解了
当你创建Integer对象时

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

IntegerCache是什么鬼

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

看完上面两段代码,它的意思如果你定义的整型对象的值在[-128,127]之间,就直接返回IntegerCache.cache[]数组里面的某个元素,下标与值对应

在[-128,127]之外的Integer对象就不再是相同的了直接 return new Integer(i);
也就是说,如果你定义的整型对象的值在[-128,127]之间,编译器不会去再创建Integer对象,直接从IntegerCache缓存中取,哪怕你定义100个值相同的Integer对象,它都是取的同一个对象,so

        Integer a = 10;        Integer b = 10;        System.out.println(a == b);

结果是true

        Integer c = 128;        Integer d = 128;        System.out.println(c == d );

结果是false

为什么么要这么搞呢,或许是[-128,127]经常用到,Java的设计者为了提高性能就这么设计的,哎!鬼知道呢,或许就是为了出这么个面试题(哈哈)


以上为个人见解,有问题qq群511906138一起讨论

0 0
原创粉丝点击