【夯實基礎】- Integer.valueof()和Integer.parseInt()的區別


  今天在看公司代碼的時候,看到有人在將 String 轉為 int 時,用到了Integer.parseInt(String s)方法,我一直用的是Integer.valueOf(String s)方法,parseInt()方法之前只是在JavaScript中看到過,有點感興趣,就去看了一下他們的源碼。

  發現 Integer.valueof()Integer.parseInt() 的底層都是用的Integer.parseInt(String s ,int radix)這個方法。在這里給這個方法做一下解釋。

  Integer.parseInt(String s ,int radix),radix用來表示傳進來的值是什么進制的,並返回10進制的 int 類型的結果 

  比如Integer.parseInt(“A”,16),則輸出結果為10進制的10,其中16表示"A"是一個16進制的值。

  根據:Character.MIN_RADIX=2和Character.MAX_RADIX=36 則,parseInt(String s, int radix)參數中radix的范圍是在2~36之間,超出范圍會拋異常。其中s的長度也不能超出7,否則也會拋異常。其中限制在36位之內是因為數字加字母剛好可以表示到36位,比如Integer.parseInt(“Z”,36),輸出結果為35。

  以下為parseInt(String s ,Int radix)的源代碼實現。

public static int parseInt(String s, int radix) throws NumberFormatException  {  
    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, max = s.length();  
    int limit;  
    int multmin;  
    int digit;  

    if (max > 0) {  
        if (s.charAt(0) == '-') {  
            negative = true;  
            limit = Integer.MIN_VALUE;  
            i++;  
        } else {  
            limit = -Integer.MAX_VALUE;  
        }  
        multmin = limit / radix;  
        if (i < max) {  
            digit = Character.digit(s.charAt(i++),radix);  
            if (digit < 0) {  
                throw NumberFormatException.forInputString(s);  
            } else {  
                result = -digit;  
            }  
        }  
        while (i < max) {  
        // 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);  
    }  
    if (negative) {  
        if (i > 1) {  
            return result;  
        } else {    /* Only got "-" */  
            throw NumberFormatException.forInputString(s);  
        }  
    } else {  
        return -result;  
    }  
}  

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM