java.lang.*中Integer類 源代碼詳解
核心方法:
int parseInt(String s) 字符串轉爲int
Integer valueOf(String s) 字符串轉爲Integer對象
parseInt方法
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10); //默認轉化爲10進制數
}
/*
* @param s 目標字符串
* @param radix 轉化的進制
* @exception NumberFormatException if the {@code String}
* does not contain a parsable {@code int}.
*/
public static int parseInt(String s, int radix)
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}
//最小轉化爲2進制
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
//最大轉化爲36進制
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) {
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) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
//result = result * radix - digit; 這樣更好理解
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
valueOf方法
1.它本身底層調用的還是parseInt方法
2.區別於parseInt,它返回的是Integer對象
3.對於-128-127的值,它默認緩存了,執行速度更快
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
學習Java的同學注意了!!!
學習過程中遇到什麼問題或者想獲取學習資源的話,歡迎加入Java學習交流羣,羣號碼:543120397 我們一起學Java!