Integer.parseInt()和Integer.valueOf()都是將成為String轉換為Int,但是為什么Java會提供兩個這樣的方法呢,他們如果是同樣的操作,豈不是多此一舉?
我們來深挖Java源代碼一探究竟。
Integer.parseInt(),返回一個原子類型int。
Integer.valueOf(),返回的是封裝的Integer對象。
我們來看一下Integer.parseInt()的源碼實現:
public static int parseInt(String s) throws NumberFormatException { return parseInt(s,10); }
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; }
可以看到ParseInt()只是調用parseInt,並返回原子類型int。
那么valueOf呢?
public static Integer valueOf(String s, int radix) throws NumberFormatException { return Integer.valueOf(parseInt(s,radix)); } public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
我們可以看到valueOf也可以調用parseInt,然后返回Integer對象。而且它會維護一個緩存,如果int值在緩存范圍內,直接從緩存中取對象,如果不在,可以創建一個新對象。
因此,我們可以進行換算,如果我們只是需要一個int值,parseInt是合適的,而且效率要高,但是如果使用值of就多此一舉了,性能會下降。
同樣Integer,Long,Double,Float都是一樣的道理。
作者:小強聊架構
鏈接:https://www.imooc.com/article/37688?block_id=tuijian_wz