Integer的parseInt源碼分析

 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) {//如果進制小於2,拋異常
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }

        if (radix > Character.MAX_RADIX) {//如果進制大於36,拋異常
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        int result = 0;//結果初始化爲0
        boolean negative = false;//是否爲負數,默認爲false
        int i = 0, len = s.length();//得到數組長度,用i來遍歷數組
        int limit = -Integer.MAX_VALUE;//限制大小爲負的int最大值
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);//得到第一個字符
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {//如果是負數,negative賦值爲true,限制變爲int的最小值
                    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++;//判斷完成下標+1
            }
            multmin = limit / radix;
			/*
			*multmin防止數據溢出
			*如果是正數就是-2,147,483,64
			*如果是負數就是-2,147,483,64
			**/
            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) {//結果比multmin還小證明溢出了,拋異常
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;//將result擴大radix倍,integer裏面radix=10
                if (result < limit + digit) {//判斷數據是否溢出
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;//因爲這裏負數正數全是先當負數算,所以是減
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;//如果是負數直接返回,否則返回-result即正數
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章