Comparative analysis of Integer.parseInt(String s, int radix) and Integer.valueOf(String s, int radix)

background

In the code review before, I found that some students directly used "==" to judge whether two Integers are equal. Is this a problem? I believe everyone has their own opinions on this. In addition, I heard someone on the subway this morning saying that the return of Integer.parseInt(String s, int radix) is of type int, where the value of radix ranges from 2 to 36, and the length of s cannot exceed 7. Is this correct? So I write this article to express my opinion

What do Integer.parseInt and Integer.valueOf do?

You may use these two methods a lot, and you also know that the string is converted into a number for common operation, then in what scenarios to use parseInt()? In which scenarios to use valueOf()? The following is my personal opinion.
First, post the two methods to the original comment

/**
     * 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.
     *
     * <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 '\u005Cu002D'}) or plus sign
     * {@code '+'} ({@code '\u005Cu002B'}) 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

A brief translation of parseInt and valueOf is indeed to convert a string into a decimal number, and supports a variety of bases (2 to 36), valueOf calls parseInt. For example, Integer.valueOf(123, 8) and Integer.parseInt(123, 8) convert octal 123 to decimal 83. The difference is that valueOf returns an Integer type, and parseInt returns an int type.

The difference between Integer.parseInt and Integer.valueOf and source code analysis

The above simple examples illustrate the functions of the two methods, the following is mainly to discuss parseInt

Why is the value of radix in parseInt(String s, int radix) from 2 to 36

Let me first talk about why it starts at 2 instead of 0 or 1 or other values. Personal analysis is that data less than 2 is only 0/1. If you start from 1, the value can only be 0 (negative numbers are not considered). No matter it is 0, 00 or several 0s, the result is 0, which is meaningless.
Why is the upper limit 36 ​​instead of 37, 64 or other values. This starts with English. The numbers currently consist of 0-9, plus 26 English letters, for a total of exactly 36 basic elements. 2 and punctuation is not taken into account

parseInt(String s, int radix) normal data range

The above mentioned the value range of radix, then does the value range of s like what netizens say cannot exceed 7? Here is a conclusion that the analytic range is -2147483648 (-2^31)
to 2147483647 (2^31-1). But there is a prerequisite that the basic characters contained in s are arranged in order (0-9 az). Exceed the radix size.
Post the source code, you can take a look if you are interested

public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
    
    
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */

        if (s == null) {
    
    
            throw new NumberFormatException("null");
        }

        if (radix < Character.MIN_RADIX) {
    
    
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {
    
    
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        int result = 0;
        boolean negative = false;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
    
    
            char firstChar = s.charAt(0);
            if (firstChar < '0') {
    
     // Possible leading "+" or "-"
                if (firstChar == '-') {
    
    
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
    
    
                // Accumulating negatively avoids surprises near MAX_VALUE
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
    
    
                    throw NumberFormatException.forInputString(s);
                }
                if (result < multmin) {
    
    
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
    
    
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
    
    
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }
    

Integer's equals() method

In addition, many people know that Integer caches data from -128 to 127 by default, so using "==" to compare two objects in this range will return true. In fact, Integer can cache more data. You can increase the cache data size by setting the -XX:AutoBoxCacheMax= parameter. In addition, if it is to compare the size of two values, it is recommended to use Integer's parseInt method directly, which can save the boxing and unboxing process

Guess you like

Origin blog.csdn.net/jerry_player/article/details/105556090