通过查看java.lang.Integer的源码可以发现, 它们最终调用的都是
/** * Parses the string argument as a signed integer in the radix * specified by the second argument. The characters in the string * must all be digits of the specified radix (as determined by * whether {@link java.lang.Character#digit(char, int)} returns a * nonnegative value), except that the first character may be an * ASCII minus sign {@code ‘-‘} (<code>‘\u002D‘</code>) to * indicate a negative value or an ASCII plus sign {@code ‘+‘} * (<code>‘\u002B‘</code>) to indicate a positive value. The * resulting integer value is returned. * * <p>An exception of type {@code NumberFormatException} is * thrown if any of the following situations occurs: * <ul> * <li>The first argument is {@code null} or is a string of * length zero. * * <li>The radix is either smaller than * {@link java.lang.Character#MIN_RADIX} or * larger than {@link java.lang.Character#MAX_RADIX}. * * <li>Any character of the string is not a digit of the specified * radix, except that the first character may be a minus sign * {@code ‘-‘} (<code>‘\u002D‘</code>) or plus sign * {@code ‘+‘} (<code>‘\u002B‘</code>) provided that the * string is longer than length 1. * * <li>The value represented by the string is not a value of type * {@code int}. * </ul> * * <p>Examples: * <blockquote><pre> * parseInt("0", 10) returns 0 * parseInt("473", 10) returns 473 * parseInt("+42", 10) returns 42 * parseInt("-0", 10) returns 0 * parseInt("-FF", 16) returns -255 * parseInt("1100110", 2) returns 102 * parseInt("2147483647", 10) returns 2147483647 * parseInt("-2147483648", 10) returns -2147483648 * parseInt("2147483648", 10) throws a NumberFormatException * parseInt("99", 8) throws a NumberFormatException * parseInt("Kona", 10) throws a NumberFormatException * parseInt("Kona", 27) returns 411787 * </pre></blockquote> * * @param s the {@code String} containing the integer * representation to be parsed * @param radix the radix to be used while parsing {@code s}. * @return the integer represented by the string argument in the * specified radix. * @exception NumberFormatException if the {@code String} * does not contain a parsable {@code int}. */ public static int parseInt(String s, int radix) throws NumberFormatException { }
这个parseInt是可以将字符串解析为各种进制的整数的, parseInt(String s)只是radix=10时的特例
而Integer.parseInt() 和 Integer.valueOf() 的区别主要在于放回的类型上, 一个是 int, 一个是Integer, 如果需要的是int, 性能上parseInt()会好点
public static Integer valueOf(String s) throws NumberFormatException { return Integer.valueOf(parseInt(s, 10)); }
这里面调用的是 valueOf(int i) 方法, 其源码中为 -128 ~ 128 之间的Integer对象很贴心地做了缓存以提高效率
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); }
时间: 2024-10-06 13:46:07