先來看段代碼 先看一下 String.valueOf() 裡面是怎麼寫的 String.valueOf() 在遇到 null 和 空串的情況下 ,都能正常輸出,所以不拋錯 再來看下 包裝類型 Integer裡面又是如何處理的 這兩個方法裡面都需要先 parseInt( s,10),就是將字元串s先轉 ...
先來看段代碼
public class IntegerDemo { public static void main(String[] args) { String num = null; System.out.println( Integer.parseInt(num));// Exception java.lang.NumberFormatException System.out.println( Integer.valueOf(num));// Exception java.lang.NumberFormatException System.out.println( String.valueOf(num)); //輸出null num = ""; System.out.println( Integer.parseInt(num)); // Exception java.lang.NumberFormatException System.out.println( Integer.valueOf(num)); // Exception java.lang.NumberFormatException System.out.println( String.valueOf(num));//空串,啥也不輸出 } }
先看一下 String.valueOf() 裡面是怎麼寫的
String.valueOf() 在遇到 null 和 空串的情況下 ,都能正常輸出,所以不拋錯
再來看下 包裝類型 Integer裡面又是如何處理的
這兩個方法裡面都需要先 parseInt( s,10),就是將字元串s先轉成 十進位的 int基本類型,,但是 valueOf()會根據int範圍從[-127,127]的內部緩存中去取(用到設計模式中的 享元模式)
一起來看下 parseInt(s, 10),,在方法裡面會判斷字元串是否是合法的數字,會去校驗null, 空串等其他格式,所以會拋錯
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; }