方法public static int parseInt(String str) 和 public static int parseInt(String str,int redix)
它是如何运作的?
&安培;他们之间有什么区别?
答案 0 :(得分:4)
至于差异:
第一个假设String是十进制表示,而第二个假设另一个参数是表示的基础(二进制,十六进制,十进制等)。
(parseInt(String str)
实现为返回parseInt(str, 10)
)
答案 1 :(得分:1)
哦,java,开源有多好。来自JDK6中的Integer:
/**
* Parses the specified string as a signed decimal integer value. The ASCII
* character \u002d ('-') is recognized as the minus sign.
*
* @param string
* the string representation of an integer value.
* @return the primitive integer value represented by {@code string}.
* @throws NumberFormatException
* if {@code string} cannot be parsed as an integer value.
*/
public static int parseInt(String string) throws NumberFormatException {
return parseInt(string, 10);
}
和基数:
/**
* Parses the specified string as a signed integer value using the specified
* radix. The ASCII character \u002d ('-') is recognized as the minus sign.
*
* @param string
* the string representation of an integer value.
* @param radix
* the radix to use when parsing.
* @return the primitive integer value represented by {@code string} using
* {@code radix}.
* @throws NumberFormatException
* if {@code string} cannot be parsed as an integer value,
* or {@code radix < Character.MIN_RADIX ||
* radix > Character.MAX_RADIX}.
*/
public static int parseInt(String string, int radix) throws NumberFormatException {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
throw new NumberFormatException("Invalid radix: " + radix);
}
if (string == null) {
throw invalidInt(string);
}
int length = string.length(), i = 0;
if (length == 0) {
throw invalidInt(string);
}
boolean negative = string.charAt(i) == '-';
if (negative && ++i == length) {
throw invalidInt(string);
}
return parse(string, i, radix, negative);
}
答案 2 :(得分:0)
它们基本上是相同的功能。 parseInt(String str)
假定为-10(除非字符串以0x
或0
开头)。 parseInt(String str, int radix)
使用给定的基数。我没有查看代码,但我打赌第一个只是调用parseInt(str, 10)
(除了那两个特殊情况,它将使用16
和8
)。