最近在网上看到一个有意思的笔试题目,题目是考察Integer类的valueOf(String s),题目如下:
以下四行代码输出的结果依次是什么?
System.out.println(Integer.valueOf("1000")==Integer.valueOf("1000"));
System.out.println(Integer.valueOf("128")==Integer.valueOf("128"));
System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));
System.out.println(Integer.valueOf("-128")==Integer.valueOf("-128"));
System.out.println(Integer.valueOf("-1000")==Integer.valueOf("-1000"));
笔主看到这个题目,就想当然的给出了自己的答案。答案如下:
false
false
false
false
false
之所以得出这个错误答案,是因为笔主认为valueOf(String s)每次返回的都是新创建的对象。为了验证自己的答案是否正确,就使用IDE写了这几行代码,运行后得到了如下答案:
System.out.println(Integer.valueOf("1000")==Integer.valueOf("1000")); --false
System.out.println(Integer.valueOf("128")==Integer.valueOf("128")); --false
System.out.println(Integer.valueOf("127")==Integer.valueOf("127")); --true
System.out.println(Integer.valueOf("-128")==Integer.valueOf("-128")); --true
System.out.println(Integer.valueOf("-1000")==Integer.valueOf("-1000")); --false
惊不惊喜,意不意外,想当然给出的答案是错误的!!!笔主这时候内心有了疑惑,为什么结果既有false又有true呢?为什么正确的答案是这样?为了消除内心的疑惑,认真看了Integer类valueOf(String s)的源码,如下:
/**
* 此方法先调用 public static int parseInt(String s, int radix)将String类型转换为int,
* 然后又调用了public static Integer valueOf(int i)方法返回Integer类型对象
*/
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
我们需要重点关注下Integer的valueOf(int i)的源码,如下:
/**
* IntegerCache是Integer的私有静态内部类,看这个名字可以猜测到这个类和缓存有关系:
* IntegerCache.low的值是-128
* IntegerCache.high的值是127
* 这个方法的作用就是当-128<=i<=127时,从IntegerCache类的数组中取出一个Integer对象,否则就新创建一个Integer对象。
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
看了这段源码之后,笔主内心的疑惑消除了。题目中-128和127在缓存的范围之内会使用缓存的对象,而-1000、128、1000在范围之外会创建的新的对象,所以才有了false、false、true、true、false这个答案。虽然解决了内心的疑惑,但是有必要好好了解下IntegerCache这个类。了解一个类最快的方法当然是看源码,如下:
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
* JLS要求通过缓存来支持在-128(包括)和127(包括)之间的数值自动装箱为同一对象。
*
* The cache is initialized on first usage. The size of the cache
* may be controlled by the {@code -XX:AutoBoxCacheMax=} 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.
*缓存会在第一次使用Integer这个类时被初始化。缓存数组的大小可以被--XX:AutoBoxCacheMax选项控制。在VM初始化时, IntegerCache.high
*属性可以被设置保存在sun.misc.VM类的私有系统配置中。
*/
private static class IntegerCache {
static final int low = -128; //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); //取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; //将high的值设置为127
cache = new Integer[(high - low) + 1]; //创建数组,length=127-(-128)+1=256
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++); //数组的值从-128至127
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {}
}
通过IntegerCache类的注释来看,和其他系统属性一样,在JVM启动时,cache数组的大小是可以通过设置-Djava.lang.Integer.IntegerCache.high=xxx传递进来的。
通过这个笔试题目,我们学习到Integer这个类是有缓存的。众所周知,Java中除了Integer还有其他类型的包装类。那么其他类型包装类存在缓存吗?答案是:除了Float和Double,其他包装类也存在缓存。
在包装类中,缓存的基本数据类型值的范围如下:
包装类型 | 基本数据类型 | 缓存范围 |
---|---|---|
Boolean | boolean | true,false |
Byte | byte | -128~127 |
Short | short | -128~127 |
Character | char | 0~127 |
Integer | int | -128~127 |
Long | long | -128~127 |
Float | float | 无 |
Double | double | 无 |
Boolean、Byte、Short、Character 、Long类型的缓存原理和Integer类型的相似,源码中均有体现。由于篇幅问题,这里不再逐一赘述。
学习到这里,我们可以总结下:
部分包装类提供了对象的缓存,实现方式是在类初始化时提前创建好会频繁使用的包装类对象,当需要使用某个包装类的对象时,如果该对象包装的值在缓存的范围内,就返回缓存的对象,否则就创建新的对象并返回。
由于笔主水平有限,笔误或者不当之处还请批评指正。