预备知识:
Java的自动装箱与拆箱:
自动装箱时编译器调用**valueOf(而非构造函数啥的)**将原始类型值转换成对象,同时自动拆箱时,编译器通过调用类似intValue(),doubleValue()这类的方法将对象转换成原始类型值。
自动装箱是将boolean值转换成Boolean对象,byte值转换成Byte对象,char转换成Character对象,float值转换成Float对象,int转换成Integer,long转换成Long,short转换成Short,自动拆箱则是相反的操作。
例如:
Integer a = 999;
相当于 Integer a = Integer.valueOf(999);
类似Integer之类的封装类的结构都很相似,有一个value成员存放原始类型,也就是封装类实际携带的数据。有一堆用于限制这个value值的静态不可变成员防止程序运行出错。
以及一堆类型之间转换的方法。
比如toString(),
下面来看一下这个valueOf()
/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} 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.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
*
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
我们翻译一下注释,这个方法将会接受一个int型的参数,返回一个代表个这个nt值的Integer实例,如果没必要new出来一个Integer对象的话 (这里的没必要指的是若传入的int值在-128~127(当然也可以在jvm启动时通过-Djava.lang.Integer.IntegerCache.high=巴拉巴拉巴拉来改变上限,但是下限是固定死的-128),将会返回一个在缓存数组里的Integer实例(这里的数组是在首次使用时(整个Integer类只有这个valueOf方法使用到这个缓存类,也可以视为在第一次给Integer装箱或者第一次直接调用)就会建立好的一个final static Integer数组),作者还说,java通过这种缓存机制显著提升了效率,节省了空间。
然后我们再看一下这简短的三行代码,首先他会判断传入int值是否在缓存范围内,若在缓存范围内,则会返回缓存类里的缓存数组中的值为传入int参数的值的Integer实例,另外注意这里的取值方法是直接通过 i+(-IntegerCache.low) 作为索引来取值,我们不难才出来,缓存类的缓存数组的索引x与值y的关系为
y = f(y +(-IntegerCache.low)) = f(y+128)
y = f(x) = x-128(索引x的取值范围在[0~231-1]故y的最大取值范围在-128~231-129)
可以得出来这里的缓存数组是[-128,-127,-126,-125…max(127或者启动时自定义的值)]
通过代码看出来,valueOf方法用到了IntegerCachel类的low,high,cache[],我们继续看一下这个缓存类的源码:
/**
* 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() {}
}
这里的注释就不再翻译了,在看valueOf注释的时候就已经解释的差不多了。大致意思就是这个类将会缓存-128~127的Integer值,并且将会在自动装箱时使用到这个缓存类。
他的代码逻辑也十分简单,首先在初始化时将会把缓存的最小值写死为-128,然后读取启动参数java.lang.Integer.IntegerCache.high,若读取的字符串不是数字,嗯/就忽略他。。。
// If the property cannot be parsed into an int, ignore it.
这里先将取到的启动参数的值与127比较去较大的(为保证缓存数组最大值大于127)。在于231-1比较去较小的(为保证数组最大索引不超过int最大值231-1)这样确定了high
然后从从low到high一个个把数填进去。
下面这里的assert我搜了下叫断言,应该是在debug模式下类似于条件断点的功能,正常运行的时候不会触发。