版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fragrant_no1/article/details/83829345
#源码解析如下
public static int parseInt(String s, int radix)
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
//需要转换的字符串是否为null
if (s == null) {
throw new NumberFormatException("null");
}
//一下两个if用于判断基数(也就是进制)是否在 2~36之间,比如10进制的数字,radix就填写10
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; //-2147483647 默认取最大整数的取反值
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 值 ,multmin = -214748364 负数跟整数的limit是不同的
multmin = limit / radix;
//开始循环追加数字,比如输入“123” 10进制数
while (i < len) {
//获取字符转换成对应进制的整数,如上,这里第一次循环获取1
//第二次循环获取2
//第三次循环获取3
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
/*/判断,在追加后一个数字前,判断其是否能能够在继续追加数字,比如multmin = 123
那么再继续追加就会变为123*10+下一个数字,就会溢出
*/
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
//第一次循环 result = 0;
//第二次循环 result = -10;
//第三次循环 result = -120;
result *= radix;
/*
用于判断下一个准备追加的数字是否可以追加,比如result现在是120,那么,如果digit是5,
那么追加后就会变为125,已经超过123的限制了,注意这里是limit而不是multmin
*/
if (result < limit + digit) {
//第一次循环 limit + digit = -214748364+1;
//第二次循环 limit + digit = -214748364+2;
//第三次循环 limit + digit = -214748364+3;
throw NumberFormatException.forInputString(s);
}
result -= digit;
//第一次循环 result = -1;
//第二次循环 result = -12;
//第三次循环 result = -123;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
//negative 值为false,所以 -result = -(-123) = 123 返回结果
}