JDK 原始碼 Integer解讀之一(parseInt)

雨露發表於2019-01-19
  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好像沒有多少內容,就先這樣吧。

相關文章