JDK 源码 Integer解读之三(valueOf)

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的值。

相关推荐