美文网首页
String 转换成 Integer 的方式及原理

String 转换成 Integer 的方式及原理

作者: dlihasa | 来源:发表于2019-03-05 14:49 被阅读27次
方式

String转换成Integer的方法有很多,比较常见的:

public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
}
public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
}

调用方式:

Integer.parseInt(String s)
Integer.valueOf(String s)

除了这两种方法外,Integer还有很多其他的方法,但是不管是哪种方法,其内部最终还是会调用parseInt(String s, int radix)这个方法。

常用方法之一:

/**
     * Parses the string argument as a signed decimal integer. The
     * characters in the string must all be decimal digits, except
     * that the first character may be an ASCII minus sign {@code '-'}
     * (<code>'&#92;u002D'</code>) to indicate a negative value or an
     * ASCII plus sign {@code '+'} (<code>'&#92;u002B'</code>) to
     * indicate a positive value. The resulting integer value is
     * returned, exactly as if the argument and the radix 10 were
     * given as arguments to the {@link #parseInt(java.lang.String,
     * int)} method.
     *
     * @param s    a {@code String} containing the {@code int}
     *             representation to be parsed
     * @return     the integer value represented by the argument in decimal.
     * @exception  NumberFormatException  if the string does not contain a
     *               parsable integer.
     */
    public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }

这个方法的前半段注释可以翻译为:

将字符串参数解析为带符号的十进制整数。该字符串中的字符必须都是十进制数字,除了第一个字符可以是ASCII减号以表示负值,或者ASCII加号表示正值。

最终调用方法
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.
         */
        //判断字符是否为null
        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;
        //char字符数组下标和长度
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;
        //判断字符长度是否大于0,否则抛出异常
        if (len > 0) {
            //由于第一个字符的特殊性,取出第一个字符先判断其符号位
            char firstChar = s.charAt(0);
            //根据ascii码表看出加号(43)和负号(45)对应的
            //十进制数小于‘0’(48)的
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {//是负号
                    negative = true;//负号属性设置为true
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')//不是负号也不是加号则抛出异常
                    throw NumberFormatException.forInputString(s);
                //如果有符号(加号或者减号)且字符串长度为1,则抛出异常
                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);
                //小于0,则为非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;
    }

上述代码中写了部分注释来对转换过程说明,除此之外,需要再看一下上面方法中调用的方法Character.digit(char ch, int radix)

public static int digit(int codePoint, int radix) {
        //基数必须再最大和最小基数之间
        if (radix < MIN_RADIX || radix > MAX_RADIX) {
            return -1;
        }
        
        if (codePoint < 128) {
            // Optimized for ASCII
            int result = -1;
            //字符在0-9字符之间
            if ('0' <= codePoint && codePoint <= '9') {
                result = codePoint - '0';
            }
            //字符在a-z之间
            else if ('a' <= codePoint && codePoint <= 'z') {
                result = 10 + (codePoint - 'a');
            }
            //字符在A-Z之间
            else if ('A' <= codePoint && codePoint <= 'Z') {
                result = 10 + (codePoint - 'A');
            }
            //通过判断result和基数大小,输出对应值
            //通过我们parseInt对应的基数值为10,
            //所以,只能在第一个判断(字符在0-9字符之间)
            //中得到result值 否则后续程序会抛出异常
            return result < radix ? result : -1;
        }
        return digitImpl(codePoint, radix);
    }

主要流程都在代码中注释了

总结

integer.parseInt(string str)方法调用Integer内部的 parseInt(string str,10)方法,默认基数为10,parseInt内部首先 判断字符串是否包含符号(-或者+),则对相应的negative和limit进行 赋值,然后再循环字符串,对单个char进行数值计算Character.digit(char ch, int radix) 在这个方法中,函数肯定进入到0-9字符的判断(相对于string转换到int), 否则会抛出异常,数字就是如上面进行拼接然后生成的int类型数值。

相关文章

网友评论

      本文标题:String 转换成 Integer 的方式及原理

      本文链接:https://www.haomeiwen.com/subject/kgsnuqtx.html