java.lang.Integer

The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.

In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.

Implementation note: The implementations of the “bit twiddling” methods (such as highestOneBit and numberOfTrailingZeros) are based on material from Henry S. Warren, Jr.’s Hacker’s Delight, (Addison Wesley, 2002).

parseInt()

API 使用规范 - - - Java™ SE 8 API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}

// s 为目标字符串,radix 为目标字符串的进制,默认为 10 进制
public static int parseInt(String s, int radix)
throws NumberFormatException
{

/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/


if (s == null) {
throw new NumberFormatException("null");
}

// 进制范围为 2 - 36
// Character.MIN_RADIX = 2
// Character.MAX_RADIX = 36
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; // 转换成 10 进制的结果,默认当成负数处理
boolean negative = false; // 代表正负号
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE; // 最大值限制,因为当成负数处理,所以为负数
int multmin; // 用来防止溢出
int digit; // 字符串里的字符,转换成 10 进制之后的值

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; // 在 result *= radix 之前判断,防止溢出
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix); // 无法转换时会返回 -1
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) { // 防止 result - digit 溢出
throw NumberFormatException.forInputString(s);
}
result -= digit; // 因为是当成负数处理,所以是 result - digit
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}