Integer.parseInt() 和 Integer.valueOf() 都是用来 将String转换为Int的,但是为什么Java会提供两个这样的方法呢,他们如果是同样的操作,岂不是多此一举?
我们来深挖Java源代码一探究竟。
Integer.parseInt(),返回一个原子类型int.Integer.valueOf(), 返回的是封装的Integer对象。
Integer.parseInt() 的源码实现:
public static int parseInt(String s
) throws NumberFormatException
{
return parseInt(s
,10);
}
public static int parseInt(String s
, int radix
)
throws NumberFormatException
{
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') {
if (firstChar
== '-') {
negative
= true;
limit
= Integer
.MIN_VALUE
;
} else if (firstChar
!= '+')
throw NumberFormatException
.forInputString(s
);
if (len
== 1)
throw NumberFormatException
.forInputString(s
);
i
++;
}
multmin
= limit
/ radix
;
while (i
< len
) {
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
;
}
} else {
throw NumberFormatException
.forInputString(s
);
}
return negative
? result
: -result
;
}
可以看到ParseInt() 只是调用parseInt, 并且返回原子类型int. 那么valueOf 呢?
public static Integer
valueOf(String s
, int radix
) throws NumberFormatException
{
return Integer
.valueOf(parseInt(s
,radix
));
}
public static Integer
valueOf(int i
) {
assert IntegerCache
.high
>= 127;
if (i
>= IntegerCache
.low
&& i
<= IntegerCache
.high
)
return IntegerCache
.cache
[i
+ (-IntegerCache
.low
)];
return new Integer(i
);
}
我们可以看到 valueOf 也会调用parseInt, 但是返回Integer对象。而且它会维护一个cache,如果int值在cache范围内,直接从cache中取对象,如果不在,则会新创建一个对象。
所以我们可以得出结论,如果我们只是需要一个int值,parseInt是合适的,而且效率要高,但是如果用valueOf就多此一举了,性能会下降。
同样Integer, Long, Double, Float 都是一样的道理。