Integer.parseInt 是如何工作的



方法public static int parseInt(String str)和public static int parseInt(String str, int redix)

它是如何工作的?

它们之间有什么区别?

您可以在此处阅读实现。以及此处的文档。

至于区别:

第一个假设字符串是十进制表示,

而第二个需要另一个参数,它是表示的基础(二进制、十六进制、十进制等)。

parseInt(String str) 实现为返回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);
}

它们基本上是相同的函数。 parseInt(String str)假定以 10 为基数(除非字符串以 0x0 开头)。 parseInt(String str, int radix)使用给定的基数。 我没有看过代码,但我敢打赌第一个只是调用parseInt(str, 10)(除了在两种特殊情况下它会使用 168)。

最新更新