Java基础 内部实现

时间:2024-10-14 14:06:44
public static int parseInt(String s, int radix) throws NumberFormatException { if (s == null) { throw new NumberFormatException("null"); } //判断进制解析范围,只支持2-36进制,默认是十进制,redix = 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;//解析结果的阈值,即不能解析出整型能表示的最大数 int multmin; int digit; if (len > 0) { //以下为符号检测,检测第一个字符是否是负号,并根据负号更新解析限定值,即解析结果不能超过int型最大值 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) {//结果解析已经超出限制了,因为后面还要继续*10,这里的result如果已经比Integer.MAX_VALUE/10还要大,那么数字就超了,抛出异常 throw NumberFormatException.forInputString(s); } result *= radix;//乘以10 if (result < limit + digit) {//与上一步一样,防止超出Integer表达范围 throw NumberFormatException.forInputString(s); } result -= digit; } } else { throw NumberFormatException.forInputString(s); } return negative ? result : -result;//取相反数返回 }