java的自动装箱和拆箱
java中的基本数据类型都有对应的包装类:
int -- Integer
char -- Character
byte -- Byte
double -- double
float -- Float
boolean -- Boolean
short -- Short
long -- Long
包装类和基本类型就涉及到自动装箱和拆箱,例如:
Integer i=3; //自动装箱 (怎么记忆呢? 把基本类型自动转换为包装类型 基-包装)
int j=i; //自动拆箱 (包装类型拆掉变成基本类型)
缓存池:
Integer默认缓冲池为一个数组,范围为-128~127,jdk1.8之后可以通过更改jvm的配置改变上界大小。
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;
}
自动装箱会调用Integer.valueOf()方法,来看看这个方法:
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);
}
也就是说如果是在范围内,则
Integer cc = 100;
Integer aa=100;
aa==cc //true