引言
包裝數據類直接賦值,默認調用其對用的valueOf()方法:
Integer i = 10;
反編譯查看:
Integer i = Integer.valueOf(10);
一、整型
Byte.valueOf(byte b)
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
private static class ByteCache {
private ByteCache(){}
static final Byte cache[] = new Byte[-(-128) + 127 + 1]; /*數組大小256*/
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Byte((byte)(i - 128)); /* -128 ~ 127 */
}
}
Short.valueOf(short s)
public static Short valueOf(short s) {
final int offset = 128;
int sAsInt = s;
if (sAsInt >= -128 && sAsInt <= 127) { // must cache
return ShortCache.cache[sAsInt + offset];
}
return new Short(s);
}
Integer.valueOf(int i)
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Long.valueOf(long l)
public static Long valueOf(long l) {
final int offset = 128;
if (l >= -128 && l <= 127) { // will cache
return LongCache.cache[(int)l + offset];
}
return new Long(l);
}
(1)-128 ~ 127之內的整型,第一次引用,在緩存中new一個對象;再次引用,直接從緩存中查找;
(2)-128 ~ 127之外的整型,每次都要new一個對象;
二、浮點型
Float.valueOf(float f)
public static Float valueOf(float f) {
return new Float(f);
}
Double.valueOf(double d)
public static Double valueOf(double d) {
return new Double(d);
}
浮點型每次都要new一個對象;
三、字符型
public static Character valueOf(char c) {
if (c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
}
private static class CharacterCache {
private CharacterCache(){}
static final Character cache[] = new Character[127 + 1];
static {
for (int i = 0; i < cache.length; i++)
cache[i] = new Character((char)i);
}
}
(1)‘0’~'127’之內的字符,存在緩存中:第一次引用,在緩存中new一個對象;再次引用,則直接從緩存中查找;
(2)‘0’~'127’之外的字符,每次都會new一個對象;
四、布爾型
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}