JDK 原始碼 Integer解讀之三(valueOf)

雨露發表於2019-01-19

1.按照以前的方法,我們先通過main函式,斷點除錯到valueOf()方法之中,
public static void main ( String[] arg ) {

System.out.println( Integer.valueOf( -300000 ));

}
情況一:進入valueOf(int i)的方法之中
public static Integer valueOf(int i) {

    if (i >= IntegerCache.low && i <= IntegerCache.high)  (1)
        return IntegerCache.cache[i + (-IntegerCache.low)]; (2)
    return new Integer(i); (3)

}
通過(1)我們知道,首先會先呼叫IntegerCache快取,快取的區間是-127到128,-300000不再-127與128之間,所以直接返回new Integer(-300000),假設一開始的值位-50的話,直接從快取中返回。

情況二:進入valueOf(string i)的方法之中
public static Integer valueOf(String s) throws NumberFormatException {

    return Integer.valueOf(parseInt(s, 10));

}

public static Integer valueOf(String s, int radix) throws NumberFormatException {

    return Integer.valueOf(parseInt(s,radix));

}
通過這兩個方法即可得知,都會進入valueOf(parseInt(s, 10))的方法,接下來我們進入這個方法裡面,
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`) { // Possible leading "+" or "-"
            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);
            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;
}

可以參照Integer解讀之二parseInt()即可得知Integer的本質其實就是利用字串陣列,將陣列中的每一個字元,強制型別轉換位int數字,乘以相應的進位制,最後累加,獲取的int的值。

相關文章