Java中那些不得不说的坑

来源:互联网 发布:hold the door知乎 编辑:程序博客网 时间:2024/05/13 05:51

看看下面这段代码跟你想的结果一样吗?

        Integer a =127;        Integer b = 127;        System.out.println(a==b);//true        Integer a1 = 128;        Integer b1 = 128;        System.out.println(a1==b1);//false

为什么会是这样的结果,我们反编译.class文件看看

    Integer a = Integer.valueOf(127);    Integer b = Integer.valueOf(127);    System.out.println(a == b);    Integer a1 = Integer.valueOf(128);    Integer b1 = Integer.valueOf(128);    System.out.println(a1 == b1);

其实是Integer作者在写这个类时,为了避免重复创建对象,对一定范围的Integer做了缓存,如果该值没有在该范围内则new一个新对象返回,从源码中可以看到如下代码:

    public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)]; //i如果在该范围内直接返回缓存值        return new Integer(i);    }

IntegerCache 是Integer 类的静态内部类,再来看看IntegerCache的实现

 private static class IntegerCache {        static final int low = -128;        static final int high;        static final Integer cache[];        static {//当类被载入到java虚拟机是进行缓存创建            // 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() {}    }