Java Short.parseShort 和 Short.valueOf 之间的区别

Java difference between Short.parseShort and Short.valueOf

我最近在 Stack Overflow 上偶然发现 another question,其中有人建议使用 Short.parseShort(String s) 和另一个人 Short.valueOf(String s)。

我自己都试过了,我发现功能上没有区别,而且 official Documentation 也没有真正帮助我:

Short.parseShort: Parses the string argument as a signed decimal short. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting short value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseShort(java.lang.String, int) method.

Short.valueOf: Returns a Short object holding the value given by the specified String. The argument is interpreted as representing a signed decimal short, exactly as if the argument were given to the parseShort(java.lang.String) method. The result is a Short object that represents the short value specified by the string.

两者都接受附加参数 radix,并且都抛出 NumberFormatException.

它们似乎是相同的,但如果是这样,为什么两者都存在?

valueOf 在内部使用 parseShort 并另外将值包装在盒装类型中 Short:

public static Short valueOf(String s, int radix)
    throws NumberFormatException {
    return valueOf(parseShort(s, radix));
}