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
}