java 自动拆箱和自动装箱

简单来说,装箱就是将基本类型转换为包装器类型,而拆箱就是将包装器类型转化为基本类型

java有8中基本类型:byte(1字节),short(2字节),char(2字节),int(4字节),float(4字节),long(8字节),double(8字节),boolean

那么,对应的包装类分别是:Byte,Short,Character,Integer,Float,Long,Double,Boolean

Integer num1 = 10;

//之后系统会自动帮我们执行 Integer num1 = Integer.valueOf(10); 这就是自动装箱

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

可以看出来 Integer提供了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) {
                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() {}
    }

如果值在-128 - 127 之间,那么是直接从cache中取值,但是不在这个范围就new一个Interger
 
public Integer(int value) {
        this.value = value;
    }

接着说一下Integer的构造函数

private final int value;

 public Integer(int value) {
        this.value = value;
    }

public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);  //如果是字符串的话,默认是十进制
    }


 public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */

        if (s == null) {
            throw new NumberFormatException("null");
        }
        // public static final int MIN_RADIX = 2;
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }
        // public static final int MAX_RADIX = 36;
        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        int result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        // @Native public static final int   MAX_VALUE = 0x7fffffff;
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true; 
                    //  @Native public static final int   MIN_VALUE = 0x80000000;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }


 public static int digit(char ch, int radix) {
        return digit((int)ch, radix);
    }

public static int digit(int codePoint, int radix) {
        return CharacterData.of(codePoint).digit(codePoint, radix);
    }

//接下来就看不懂了0.0.0.0.0.0.0

实验了一把  
Integer num1 = new Integer("-1234");  -1234
Integer num1 = new Integer("-asdf"); 报错
int n = i;
//这个是拆箱 调用了Integer的intValue 方法

public int intValue() {
        return value;
    }


猜你喜欢

转载自blog.csdn.net/qq_35815781/article/details/84955229