Interget.parseInt(String s, int radix)实现原理。
源码:
public static int parseInt(String s, int radix)
throws NumberFormatException
{
... // 参数合法性检查,省略
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
// 假设输入eg="25"
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);
// eg不在上两个 if else 中,negative = false
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
// 从string的第一个char开始循环向后取
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
// Character.digit(char ch, int radix),在这里的效果,对char '0'~'9'返回int 0~9
// digit方法针对ascii字符的优化
// if ('0' <= codePoint && codePoint <= '9') {
// result = codePoint - '0';
// } else if ('a' <= codePoint && codePoint <= 'z') {
// result = 10 + (codePoint - 'a');
// } else if ('A' <= codePoint && codePoint <= 'Z') {
// result = 10 + (codePoint - 'A');
// }
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
// 假设之前是 -2,对应‘2’,radix=10,当前值为5,对应‘5’
result *= radix; //效果相当于将之前获得的值进位(result是负数对应正数真实值)
// 变成 -2*10
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
// 变成 -2*10-5= -25
}
} else {
throw NumberFormatException.forInputString(s);
}
// 根据正负性返回result的正数或负数,(result是负数对应正数真实值)
return negative ? result : -result;
// negative为false,返回 -(-25)=25
}