Análise comparativa de Integer.parseInt (String s, int radix) e Integer.valueOf (String s, int radix)

fundo

Na revisão do código anterior, descobri que alguns alunos usaram diretamente "==" para julgar se dois inteiros são iguais. Isso é um problema? Eu acredito que todos têm suas próprias opiniões sobre isso. Além disso, ouvi alguém no metrô esta manhã dizendo que o retorno de Integer.parseInt (String s, int radix) é do tipo int, em que o valor de radix varia de 2 a 36 e o ​​comprimento de s não pode exceder 7. Isso está correto? Então, escrevo este artigo para expressar minha opinião

O que Integer.parseInt e Integer.valueOf fazem?

Você pode usar muito esses dois métodos e também sabe que a string é convertida em um número para operação comum. Em quais cenários usar parseInt ()? Em quais cenários usar valueOf ()? A seguir, minha opinião pessoal.
Primeiro, poste os dois métodos no comentário original

/**
     * 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

Uma breve tradução de parseInt e valueOf é, de fato, converter uma string em um número decimal e oferece suporte a uma variedade de bases (2 a 36), valueOf chama parseInt. Por exemplo, Integer.valueOf (123, 8) e Integer.parseInt (123, 8) convertem o octal 123 em decimal 83. A diferença é que valueOf retorna um tipo Integer e parseInt retorna um tipo int.

A diferença entre Integer.parseInt e Integer.valueOf e análise de código-fonte

Os exemplos simples acima ilustram as funções dos dois métodos, o seguinte é principalmente para discutir parseInt

Por que o valor de radix em parseInt (String s, int radix) é de 2 a 36

Deixe-me primeiro falar sobre por que ele começa em 2 em vez de 0 ou 1 ou outros valores. A análise pessoal mostra que os dados menores que 2 são apenas 0/1. Se você começar a partir de 1, o valor só pode ser 0 (os números negativos não são considerados). Quer seja 0, 00 ou vários 0s, o resultado é 0, o que não faz sentido.
Por que o limite superior é 36 em vez de 37, 64 ou outros valores. Isso começa com o inglês. Os números atualmente consistem em 0-9, mais 26 letras em inglês, para um total de exatamente 36 elementos básicos. 2 e a pontuação não é levada em consideração

parseInt (String s, int radix) intervalo de dados normal

O acima mencionado o intervalo de valor de radix, então o intervalo de valor de s como o que os internautas dizem não pode exceder 7? Aqui está uma conclusão de que o intervalo analítico é -2147483648 (-2 ^ 31)
a 2147483647 (2 ^ 31-1). Mas há um pré-requisito de que os caracteres básicos contidos em s sejam organizados em ordem (0-9 az). Exceda o tamanho do radical.
Poste o código-fonte, você pode dar uma olhada se estiver interessado

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;
    }
    

Método equals () de inteiro

Além disso, muitas pessoas sabem que o número inteiro armazena dados em cache de -128 a 127 por padrão, portanto, usar "==" para comparar dois objetos neste intervalo retornará verdadeiro. Na verdade, Integer pode armazenar mais dados em cache.Você pode aumentar o tamanho dos dados em cache configurando o parâmetro -XX: AutoBoxCacheMax =. Além disso, se for para comparar o tamanho de dois valores, é recomendado usar o método parseInt de Integer diretamente, que pode salvar o processo de encaixotamento e desempacotamento

Acho que você gosta

Origin blog.csdn.net/jerry_player/article/details/105556090
Recomendado
Clasificación