0%

字符串和数字转换

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Test {
public static void main(String[] args) {
String str = "123";

Integer num1 = new Integer(str);

int num2 = Integer.parseInt(str);

Integer num3 = Integer.valueOf(str);

System.out.println(num1 + "\t" + num2 + "\t" + num3);//123 123 123
}
}

在上面代码中,演示了三个方式的转化,分别是new了新对象和调用静态方法,我们查看内部的变化

Interger 类的构造函数

1
2
3
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}

从代码中看的,构造函数时调用了一个parseInt(s,10)的内部函数

parseInt(s)

1
2
3
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}

从代码中看到也是调用了一个parseInt(s,10)的内部函数

Integer.valueOf(s)

1
2
3
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}

从代码中看到也是调用了一个 parseInt(s,10) 的内部函数
我们可以看出其实都调用了 parseInt(String s,int radix); 让我们看看他内部实现

parseInt(String s,int radix)

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
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");
}

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) {
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++;
}
......
......
......
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}

从代码中看出,==字符串不能为空值以及字符串得为数字==,不然会报异常( NumberFormatException )

本文标题:字符串和数字转换

文章作者:志者

发布时间:2019年08月16日 - 15:49:00

最后更新:2019年08月28日 - 17:33:45

原始链接:http://witman1999.github.io/字符串与数字转换.html

许可协议: 署名-非商业性使用-相同方式共享 4.0 国际 转载请保留原文链接及作者。

-------------本文结束感谢您的阅读-------------
copy