JDK 源码 Integer解读之一(parseInt)

  1. 首先,我们通过断点调试,一步一步揭开parseInt的技术内幕
    public static void main ( String[] arg ) {
    System.out.println( Integer.parseInt( "18" ));
    }

我们进入了这个方法之中
public static int parseInt(String s) throws NumberFormatException {

return parseInt(s,10);(1)

}
通过(1)这个方法可知,我们是调用了 parseInt(s,10)这个方法,默认注入的进制是十进制。
接下来,我们将重点研究 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) { (1)
        throw new NumberFormatException("null");
    }

    if (radix < Character.MIN_RADIX) { (2)
        throw new NumberFormatException("radix " + radix +
                                        " less than Character.MIN_RADIX");
    }

    if (radix > Character.MAX_RADIX) {  (3)
        throw new NumberFormatException("radix " + radix +
                                        " greater than Character.MAX_RADIX");
    }

    int result = 0;
    boolean negative = false;
    int i = 0, len = s.length();   (4)
    int limit = -Integer.MAX_VALUE;
    int multmin;
    int digit;

    if (len > 0) {
        char firstChar = s.charAt(0);  (5)
        if (firstChar < '0') { // Possible leading "+" or "-" (6)
            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; 
        while (i < len) { 
            // Accumulating negatively avoids surprises near MAX_VALUE
            digit = Character.digit(s.charAt(i++),radix); (7)
            if (digit < 0) {
                throw NumberFormatException.forInputString(s);
            }
            if (result < multmin) {
                throw NumberFormatException.forInputString(s);
            }
            result *= radix; (8)
            if (result < limit + digit) {
                throw NumberFormatException.forInputString(s);
            }
            result -= digit;  (9)
        }
    } else {
        throw NumberFormatException.forInputString(s);
    }
    return negative ? result : -result; (10)
}

首先,在(1)到(3)中进行数字的判断,保证数据不为空,并且只支持2-36进制之间的进制方式,在(4)中先计算出S的长度,在(5)处,获取S的第一个字符1,对应的是49,将49赋值给 firstChar,在(6)处判断是否为负数,在(7)处可以得到正数第一位,负数第二位的数值,在(8)与(9)在通过乘以进制数,最后在-得到十位,个位上的值等。parseInt好像没有多少内容,就先这样吧。

相关推荐