メソッド public static int parseInt(String str) および public static int parseInt(String str, int redix)
それはどのように機能しますか?
&それらの違いは何ですか?
メソッド public static int parseInt(String str) および public static int parseInt(String str, int redix)
それはどのように機能しますか?
&それらの違いは何ですか?
You can read the implementation here. And the documentation here.
As for the difference:
The first assumes the String to be a decimal representation, while the second expects another parameter which is the base of the representation (binary, hex, decimal etc.)
( parseInt(String str)
is implemented as return parseInt(str, 10)
)
ああ、Java はオープン ソースです。JDK6の整数から:
/**
* 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);
}
They are basically the same function. parseInt(String str)
assumes base-10 (unless the string starts with 0x
or 0
). parseInt(String str, int radix)
uses the given base. I haven't looked at the code but I bet the first simply calls parseInt(str, 10)
(except in those two special cases where it'll use 16
and 8
).