1.两个方法都可以把数字类型字符串转成int类型整数,valueOf(String s)方法调用了parseInt(String s, int radix)方法,返回值是Integer类型。parseInt方法返回值是一个int类型 之后又要调用valueOf(int i)方法将其包装成Integer。
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static int parseInt(String s, int radix)
throws NumberFormatException
{
/* 警告:在初始化IntegerCache之前,VM初始化期间可能会提前调用此方法。 必须注意不要使用valueOf方法。
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
//字符串为空则抛出NumberFormatException
if (s == null) {
throw new NumberFormatException("null");
}
//传的进制参数小于2,抛出NumberFormatException,并且提示进制小于最小进制
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
//传的进制参数小于36,抛出NumberFormatException,并且提示进制小于最大进制
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
//negative 用来判断结果是否为负数
boolean negative = false;
//获取字符串长度
int i = 0, len = s.length();
//limit = -2147483647
int limit = -Integer.MAX_VALUE;
//用于在添加下一位数字的前判断是否溢出的值
int multmin;
//需要追加的数字
int digit;
//字符长度大于0
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 != '+')
//不为负数或正数,抛出NumberFormatException
throw NumberFormatException.forInputString(s);
//长度为1,抛出NumberFormatException
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
//计算 multmin ,注意负数和正数的limit是不一样的,负数的limit = -2147483648,正数的limit = -2147483647
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 {
//字符不为空,但是字符长度等于0,抛出NumberFormatException
throw NumberFormatException.forInputString(s);
}
//根据正负数的标识来判断结果取正还是取反
return negative ? result : -result;
}