背景
之前在code review 的时候,发现有同学直接使用“==”判断两个Integer是否相等,这有问题吗?相信大家对这个都有自己对看法。另外今早上在地铁上听到有人说Integer.parseInt(String s, int radix)返回是int类型,其中radix取值范围是2~36,s长度不能超过7,这种说法对吗?故写此文章来发表自己看法
Integer.parseInt和Integer.valueOf是做什么的?
大家可能对这两个方法用的都比较多,也知道是将string转换成数字共运算,那什么场景下使用parseInt()?什么场景下使用valueOf()?以下是我个人见解。
首先分别把两个方法对原文注释贴一下
/**
* Returns an {@code Integer} object holding the value
* extracted from the specified {@code String} when parsed
* with the radix given by the second argument. The first argument
* is interpreted as representing a signed integer in the radix
* specified by the second argument, exactly as if the arguments
* were given to the {@link #parseInt(java.lang.String, int)}
* method. The result is an {@code Integer} object that
* represents the integer value specified by the string.
*
* <p>In other words, this method returns an {@code Integer}
* object equal to the value of:
*
* <blockquote>
* {@code new Integer(Integer.parseInt(s, radix))}
* </blockquote>
*
* @param s the string to be parsed.
* @param radix the radix to be used in interpreting {@code s}
* @return an {@code Integer} object holding the value
* represented by the string argument in the specified
* radix.
* @exception NumberFormatException if the {@code String}
* does not contain a parsable {@code int}.
*/
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}
/**
* 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 '\u005Cu002D'}) to
* indicate a negative value or an ASCII plus sign {@code '+'}
* ({@code '\u005Cu002B'}) 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.
*