包装类的Integer类源码解析(除了Boolean、Character,其他5种包装类几乎一致)

public final class Integer extends Number implements Comparable<Integer>{
	@Native public static final int   MIN_VALUE = 0x80000000;//int数值的最小值
	@Native public static final int   MAX_VALUE = 0x7fffffff;//int数值的最大值
	public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
	final static char[] digits = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    };//创建一个数组
    //将i按照radix进制转为字符串
    //i表示10进制数,radix表示进制数
    public static String toString(int i, int radix) {
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)//如果进制数不合理,强制转为10进制
            radix = 10;
        //如果是十进制,直接返回i的字符串
        if (radix == 10) {
            return toString(i);
        }
		
        char buf[] = new char[33];//进制的最大数组
        boolean negative = (i < 0);
        int charPos = 32;
		//如果i为正数,则强制转为负数
        if (!negative) {
            i = -i;
        }
		//10进制转为radix进制,用10除以radix,保存每次相除后的余数,作为相乘因子
        while (i <= -radix) {
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        //保存最后的余数
        buf[charPos] = digits[-i];
		//如果i为负数,buf数组最后一个元素为-
        if (negative) {
            buf[--charPos] = '-';
        }
		//然后将数组反过来转为字符串
        return new String(buf, charPos, (33 - charPos));
    }
    //调用的Long的toUnsignedString方法,下面会有说明
	public static String toUnsignedString(int i, int radix) {
        return Long.toUnsignedString(toUnsignedLong(i), radix);
    }
    //这个地方采用的是二分法
    //计算i的二进制补码中最高位连续为0的个数
    public static int numberOfLeadingZeros(int i) {
        if (i == 0)
            return 32;
        int n = 1;
        if (i >>> 16 == 0) { n += 16; i <<= 16; }
        if (i >>> 24 == 0) { n +=  8; i <<=  8; }
        if (i >>> 28 == 0) { n +=  4; i <<=  4; }
        if (i >>> 30 == 0) { n +=  2; i <<=  2; }
        n -= i >>> 31;
        return n;
    }
	//将i转化为16进制
	public static String toHexString(int i) {
        return toUnsignedString0(i, 4);
    }
    //将i转化为8进制
	public static String toOctalString(int i) {
        return toUnsignedString0(i, 3);
    }
    //将i转化为2进制
	public static String toBinaryString(int i) {
        return toUnsignedString0(i, 1);
    }
    //这个涉及二进制计算,不做深究
    //将整数转换为无符号数字
	private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
        int chars = Math.max(((mag + (shift - 1)) / shift), 1);
        char[] buf = new char[chars];

        formatUnsignedInt(val, shift, buf, 0, chars);

        // Use special constructor which takes over "buf".
        return new String(buf, true);
    }
    //十位上的数组
	final static char [] DigitTens = {
        '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
        '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
        '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
        '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
        '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
        '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
        '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
        '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
        '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
        '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
        } ;
    //个位上的数组
    final static char [] DigitOnes = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        } ;
    //保存不同位数的最大值
    final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
                                      99999999, 999999999, Integer.MAX_VALUE };
    //返回x的位数
    //思路:先循环判断x小于某个位数的最大值,说明x的位数就是该最大值的位数
    static int stringSize(int x) {
        for (int i=0; ; i++)
            if (x <= sizeTable[i])
                return i+1;
    }
    //将i转化为String
	public static String toString(int i) {
        if (i == Integer.MIN_VALUE)
            return "-2147483648";
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);//保存i的位数
        char[] buf = new char[size];
        getChars(i, size, buf);
        return new String(buf, true);
    }
    //将i从低位开始index索引位置转化为字符数组
    static void getChars(int i, int index, char[] buf) {
        int q, r;
        int charPos = index;
        char sign = 0;
		//如果i是负数,添加一个标志符,然后强行转为正数
        if (i < 0) {
            sign = '-';
            i = -i;
        }		
        while (i >= 65536) {
            q = i / 100;//取最大的100倍数
            r = i - ((q << 6) + (q << 5) + (q << 2));//相当于i - q * 100,取余
            i = q;//然后将q保存到i,方便进行下一轮的取余和取模
            buf [--charPos] = DigitOnes[r];//下面两个分别用个位、十位代表余数,减少乘法运算
            buf [--charPos] = DigitTens[r];
        }
        //处理小于2的16次方的数
        for (;;) {
            q = (i * 52429) >>> (16+3);//接近于i/10
            r = i - ((q << 3) + (q << 1));  
            buf [--charPos] = digits [r];
            i = q;
            if (i == 0) break;
        }
        //符号判断
        if (sign != 0) {
            buf [--charPos] = sign;
        }
    }
    //将s按照radix进制转化为int类型
	public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        if (s == null) {
            throw new NumberFormatException("null");
        }
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }
        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();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);//保存第一个字符
            if (firstChar < '0') { //不排除有正负数标志符
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1)//不能只有一个字符
                    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;
    }
    //将s按照10进制转化为int类型
	public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }
    //将s按照radix进制转为无符号int
	public static int parseUnsignedInt(String s, int radix)
                throws NumberFormatException {
        if (s == null)  {
            throw new NumberFormatException("null");
        }

        int len = s.length();
        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar == '-') {
                throw new
                    NumberFormatException(String.format("Illegal leading minus sign " +
                                                       "on unsigned string %s.", s));
            } else {
                if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
                    (radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
                    return parseInt(s, radix);
                } else {
                    long ell = Long.parseLong(s, radix);
                    if ((ell & 0xffff_ffff_0000_0000L) == 0) {
                        return (int) ell;
                    } else {
                        throw new
                            NumberFormatException(String.format("String value %s exceeds " +
                                                                "range of unsigned int.", s));
                    }
                }
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
    }
    //将s按照10进制转为无符号int
	public static int parseUnsignedInt(String s) throws NumberFormatException {
        return parseUnsignedInt(s, 10);
    }
    //成员内部类
    //创建值为-128~127的integer时,就会把该对象放入缓冲区,第二次创建时直接从缓冲区中获得到该对象,而不在重复创建新对象;
    //而在创建值其他范围的integer时,创建的对象不会进入缓存区,两次操作都会创建新的对象
    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];
        static {
            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);
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                }
            }
            high = h;
            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
            assert IntegerCache.high >= 127;
        }
        private IntegerCache() {}
    }
    //返回i的包装类,需要判断是否需要放入缓存区
	public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    //将s按照radix进制转为Integer
	public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return Integer.valueOf(parseInt(s,radix));
    }
    //将s按照10进制转为Integer
	public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
    }
	private final int value;
	//初始化value
	public Integer(int value) {
        this.value = value;
    }
    //初始化value
	public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
    }
    //将value强转为byte,然后返回
	public byte byteValue() {
        return (byte)value;
    }
    //将value强转为short,然后返回
	public short shortValue() {
        return (short)value;
    }
    //返回value
	public int intValue() {
        return value;
    }
    //将value强转为long,然后返回
	public long longValue() {
        return (long)value;
    }
    //将value强转为float,然后返回
	public float floatValue() {
        return (float)value;
    }
    //将value强转为double,然后返回
	public double doubleValue() {
        return (double)value;
    }
    //打印value
	public String toString() {
        return toString(value);
    }
    //计算hashCode,就是value
	public static int hashCode(int value) {
        return value;
    }
    //返回hashCode
	public int hashCode() {
        return Integer.hashCode(value);
    }
    //判断包装类跟obj是否相等
	public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
    //返回nm纯数字
    public static Integer decode(String nm) throws NumberFormatException {
        int radix = 10;
        int index = 0;//nm的索引位置
        boolean negative = false;
        Integer result;
        if (nm.length() == 0)
            throw new NumberFormatException("Zero length string");
        char firstChar = nm.charAt(0);//保存nm第一个字符
        //如果第一个是标志符,index前移一位
        if (firstChar == '-') {
            negative = true;
            index++;
        } else if (firstChar == '+')
            index++;
		//如果nm标志符后是以0x或者0X开头,index 再前移2位,radix为16
        if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
            index += 2;
            radix = 16;
        }
        //如果nm标志符后是以#开头,index 再前移1位,radix为16
        else if (nm.startsWith("#", index)) {
            index ++;
            radix = 16;
        }
        //如果nm标志符后是以0开头且后面还有元素,index 再前移1位,radix为8
        else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
            index ++;
            radix = 8;
        }
		//如果nm标志符后是还有标志符,直接报错
        if (nm.startsWith("-", index) || nm.startsWith("+", index))
            throw new NumberFormatException("Sign character in wrong position");

        try {//保存按照radix进制提取的纯数字,再判断正负
            result = Integer.valueOf(nm.substring(index), radix);
            result = negative ? Integer.valueOf(-result.intValue()) : result;
        } catch (NumberFormatException e) {
            String constant = negative ? ("-" + nm.substring(index))
                                       : nm.substring(index);
            result = Integer.valueOf(constant, radix);
        }
        return result;
    }
    //返回x、y的差值
	public static int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }
    //返回Integer与anotherInteger的差值
	public int compareTo(Integer anotherInteger) {
        return compare(this.value, anotherInteger.value);
    }
    //强转为无符号的long类型
	public static long toUnsignedLong(int x) {
        return ((long) x) & 0xffffffffL;
    }
    //返回a、b的和
	public static int sum(int a, int b) {
        return a + b;
    }
    //返回a、b中的最大值
	public static int max(int a, int b) {
        return Math.max(a, b);
    }
    //返回a、b中的最小值
	public static int min(int a, int b) {
        return Math.min(a, b);
    }
}

Integer源码也相对很简单,几乎没有什么难度,其他包装类Byte、Short、Long、Float、Double基本上相同

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值