我会告诉你我为什么用Integer.ValueOf()而不用new Integer()吗?
问题:当你需要产生一个整形的包装类的实例的时候(比如整数10),有两种方式:
第一种,使用构造函数new 一个对象:
Integer i=new Integer(10);
第二种,使用静态工厂方法产生实例(我会告诉你其实java里所有的ValueOf都是静态工厂方法吗?):
Integer i=Integer.ValueOf(10);
你选哪种?
我选第二种,为什么?因为,当你用第一种方式时每次都会产生一个新的实例,而当你使用静态工厂方法时,不一定会产生一个新的实例,注意我说的是不一定,至少这里没有产生一个新的实例,为什么,我们看源码:
/**
* Returns a <tt>Integer</tt> instance representing the specified
* <tt>int</tt> value.
* If a new <tt>Integer</tt> instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Integer(int)}, as this method is likely to yield
* significantly better space and time performance by caching
* frequently requested values.
*
* @param i an <code>int</code> value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
* @since 1.5
*/
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
这是Integer.ValueOf(int i)的源码,原来IntegerCache相当于做了一个缓存,在第一次被调用时,首先初始化生成了从-128到127共256个对象的数组,在以后凡是在这个范围内的int值都可以直接从此缓存中取,而不在再次生成Integer对象,大大提高了对象的利用率。
下面是IntegerCache的源码,这个就不解释了:
private static class IntegerCache {
static final int high;
static final Integer cache[];
static {
final int low = -128;
// high value may be configured by property
int h = 127;
if (integerCacheHighPropValue != null) {
// Use Long.decode here to avoid invoking methods that
// require Integer's autoboxing cache to be initialized
int i = Long.decode(integerCacheHighPropValue).intValue();
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - -low);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}
好了,很清楚了,之前我为什么说不一定不会new 一个新的对象,现在明白了,当你产生的数是-128到127时,不会new一个新的对象,超过这个范围时,同样是new 一个新的对象。