Integer源码分析


title: Integer源码分析
date: 2017-09-11 15:07:46
tags: java
categories: java


Integer继承了Number类,并且实现了Comparable

Number类


Number类是所有数字类的基类,它是一个抽象类,并且实现序列化的接口

其中提供了四种抽象方法,是将对应的value转换成对类型的值返回

    intValue();
    longValue();
    floatValue();
    doubleValue();

Integer类

Integer实现了Number中的所有接口(我觉得只是提供了一种安全地的转型)

  1. 构造方法

Integer只提供了两种构造方法,一种是初始化数字,一种是使用String通过内部的parseInt将字符转换成数字

public Integer(int value)

public Integer(String s) throws NumberFormatException
  1. to系列方法
  • toString方法

Integer类中,toString方法有两个,其中一个是重写了Object的toString方法, 另外两个是静态方法

#1 public String toString();

#2 public static String toString(int i);

#3 public static String toString(int i, int radix)

重写的toString是调用了#2方法

#2 的实现

public static String toString(int i) {
    if (i == Integer.MIN_VALUE)
        return "-2147483648";
    // 通过stringSize的方法获取传入i的长度,如果是负数则多一位
    int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
    // 创建一个长度为size的字符数组
    char[] buf = new char[size];
    // 获取i的字符形式给塞到buf中
    getChars(i, size, buf);
    return new String(buf, true);
}

static void getChars(int i, int index, char[] buf) {
    int q, r;
    int charPos = index;
    char sign = 0;
    // 如果i小于0则要转换为整数,记录下转换前的符号
    if (i < 0) {
        sign = '-';
        i = -i;
    }
    // 如果i大于或者等于65536需要,获取最后两位来进行处理
    while (i >= 65536) {
        q = i / 100;
        r = i - ((q << 6) + (q << 5) + (q << 2));
        i = q;
        // 各位
        buf [--charPos] = DigitOnes[r];
        // 十位
        buf [--charPos] = DigitTens[r];
    }
    // 死循环处理i,直到i为0退出循环
    for (;;) {
        // q、r两个计算,是获取i的最后一位,然后把获取出来的数字获取到预先定义的digits字符数组中的字符,并存入到buf中
        q = (i * 52429) >>> (16+3);
        r = i - ((q << 3) + (q << 1));
        buf [--charPos] = digits [r];
        i = q;
        if (i == 0) break;
    }
    // 如果不是0,则把上面的符号位加到上面去
    if (sign != 0) {
        buf [--charPos] = sign;
    }
}

#3 的实现

#3 提供了进制转换功能

public static String toString(int i, int radix) {
    // 如果进制不在2到36进制之类,则默认为10进制
    if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
        radix = 10;
    // 如果是十进制,直接调用toString方法返回
    if (radix == 10) {
        return toString(i);
    }
    
    char buf[] = new char[33];
    // 记录符号位
    boolean negative = (i < 0);
    int charPos = 32;
    // 将正数变为负数
    if (!negative) {
        i = -i;
    }

    while (i <= -radix) {
        // 取余
        buf[charPos--] = digits[-(i % radix)];
        i = i / radix;
    }
    // 将无需处理的丢到数组的最后
    buf[charPos] = digits[-i];
    // 还原符号位
    if (negative) {
        buf[--charPos] = '-';
    }

    return new String(buf, charPos, (33 - charPos));
}
  • toHexString、toOctalString、toBinaryString

这些都是调用toUnsignedString0实现的(骚代码,看不懂)

private static String toUnsignedString0(int val, int shift) {
    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);
    return new String(buf, true);
}
static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
    int charPos = len;
    int radix = 1 << shift;
    int mask = radix - 1;
    do {
        buf[offset + --charPos] = Integer.digits[val & mask];
        val >>>= shift;
    } while (val != 0 && charPos > 0);
    return charPos;
}
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;
}
  1. parse系列方法

它注释里面给了一个警告,如果初始化时提早使用valueof,那么high可能为0

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

    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) {
        // 取传入s的第一个字符
        char firstChar = s.charAt(0);
        // 比较字符的ASCALL码,+ 或者 - 的都比数字小
        if (firstChar < '0') {
            // 如果是负数,负数标记,limit设置为最小值
            if (firstChar == '-') {
                negative = true;
                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;
        // i可以看做字符串的指针
        while (i < len) {
            // 将digit转换为对应的进制数的数值
            digit = Character.digit(s.charAt(i++),radix);
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            }
            if (result < multmin) {
                throw NumberFormatException.forInputString(s);
            }
            // 每循环一次都需要乘以进制数,相当于扩大radix倍
            result *= radix;
            if (result < limit + digit) {
                throw NumberFormatException.forInputString(s);
            }
            // 因为防止溢出,所以结果集使用负数存储
            result -= digit;
        }
    } else {
        throw NumberFormatException.forInputString(s);
    }
    return negative ? result : -result;
}

好像Integer常用的也就这些方法,它其中很多方法是调用Long中的方法执行的,或者是转换成无符号的整数

你可能感兴趣的:(Integer源码分析)