什么都还来的及

java 装箱与拆箱

学习:https://www.cnblogs.com/wang-yaz/p/8516151.html 

public static void main(String [] args) {
        Integer i = 120 ;     //装箱    
        int a  = i;                   //拆箱
    }        

通过 javap -c Test.class 查看。class文件可以看到

会执行 

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

  

 

该方法表示 当 传入的 int 的值 在 -128 ~127 之间时 会从缓冲区中取出一个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;
        }

        private IntegerCache() {}
    }

  当值大于127 或着 小于 -128 时时会新建一个 Integer 

面试考察点:

    Integer a = 1; // 等价于 Integer a = valueOf(1)
    Integer b = 1;
    System.out.println(a == b); // true
   Integer c = 128;
    Integer d = 128;
    System.out.println(c == d); // false
    System.out.println(c.equals(d)); // true

  

posted @ 2018-05-21 21:08  coder_sun  阅读(148)  评论(0)    收藏  举报