先看一段代码:
public class Main{
public static void main(String[] args) {
Integer a=24;
Integer b=new Integer(24);
System.out.println(a==b);
Integer c=23;
Integer d=23;
System.out.println(c==d);
Integer e=128;
Integer f=128;
System.out.println(e==f);
}
}
运行结果:
false
true
false
是否和预想的结果一样,如果一样那么你一定对基本变量对象的缓存有所了解,a,b对比很容易看出来,b与c和e与f的对比就涉及了缓存问题了。
根据装箱可知Integer a=24等价于Integer a=Integer.valueOf(24),下面我们看一下valueOf()的源代码就清楚了:
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
可以看到当i的值在缓存范围内时,返回缓存内的对象(这个范围即为-128至128),如果超过了范围则new一个新的对象,这就很好解释了c与d和e与f的结果了
所以在使用Integer对象时,如果不超过缓存范围的情况下,尽量使用valueOf()方法而不是new新对象,避免创建多余的对象,可以提高内存的利用率
基本变量对象中除了Integer其它的对象也有对象缓存吗?答案是肯定的,下面就直接给出其它基本变量对象的valueOf()方法,就可以清楚看到它们的对象缓存情况了:
Byte:
public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
}
Short:
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);
}
Long:
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);
}
Character:
public static Character valueOf(char c) {
if (c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
}
Float和Double没有对象缓存(原因很简单,浮点数没法列举啊):
public static Float valueOf(float f) {
return new Float(f);
}
public static Double valueOf(double d) {
return new Double(d);
}