Java包装类&装箱|拆箱&常量池
Java包装类包括:Byte、Short、Integer、Long、Float、Double、Character、Boolean
装箱&拆箱
装箱:valueOf()
拆箱:xxxValue()
整型包装类
问题1:
Integer i = 500;
Integer i3 = 500;
Integer i2 = new Integer(500);
System.out.println(i==i2);
System.out.println(i==i3);
问题2:
Integer x = 10;
Integer y = 10;
Integer x1 = new Integer(10);
System.out.println(x==x1);
System.out.println(x==y);
问题1中输出:false、false
问题2中输出:true、false
解释:
Integer x = 10;
这种方式装箱(编译后)等同于Integer x = Integer.valueOf(10);
Integer类的部分源码:
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
* During VM initialization, java.lang.Integer.IntegerCache.high property
* may be set and saved in the private system properties in the
* sun.misc.VM class.
*/
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
可以看到
-
Integer类中静态持有了一个Integer缓存池[-127, 128],IntegerCache为Integer类的缓存类,默认缓存了-128~127的Integer值
-
valueOf方法当i值处于[-127, 128]范围中时直接返回缓存池中的实例
-
10在范围内所以返回true,500在范围外所以返回false
-
而
new Integer(10)
是直接在堆上创建了新的对象,故不为同一对象
Byte(Byte b = 1;
方式只会从缓存中取)、Short、Long中也有相同的现象。
Character
public static Character valueOf(char c) {
if (c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
}
Character也持有一个缓存池。
Boolean
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
Float&Double
public static Float valueOf(float f) {
return new Float(f);
}
public static Double valueOf(double d) {
return new Double(d);
}
总结一下
以下包装类持有常量池:
类 | 区间 | 设置上限 |
---|---|---|
Integer | [-128,127] | -XX:AutoBoxCacheMax= |
Short | [-128,127] | 不可设置 |
Long | [-128,127] | 不可设置 |
Byte | [-128,127] | 不可设置 |
Character | [0,127] | 不可设置 |