学的C/C++,看是JAVA,不懂原理,就像个傻瓜一样。同事写了个代码如下:
if (appMenuInfoDO.getMenuLevel() == Constant.Level.LEVEL_1) {
//balabala
} else {
//balabala
}
说明:getMenuLevel()返回的是Integer类型,Constant.Level.LEVEL_1也是Integer类型。
我就告诉他问题包装类型不能用==进行比较值。他说了句Integer在-128~127之间是从固定缓寸区中读取的。PS:我们项目中getMenuLevel()最大值不超过5。
为了明白为什么,特地看了下JDK的源码。源码注释中解释根据JLS规约设置IntegerCache在-127~128之间,并可根据{@code -XX:AutoBoxCacheMax=<size>}选项进行设置。
/**
* 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() {}
}
源码解释:在IntegerCache静态类中,放置一个名为cache的数组作为缓存区。下限low被设置为-128,high未被设置,优化时可以根据JVM参数设置其值(需要考虑JVM这样做的初衷是什么)。static作用域中,读取了一次配置文件,看看用户是否设置了high值,若设置了该值,则在(integerCacheHighPropValue,127,Integer.MAX_VALUE - (-low) -1)三者中选择一个中间值赋值给high,这是因为h代表的是缓存区Integer的上限,而数组存的下标是从0开始的,同时为保证high的值大于等于127,所有才进行了i = Math.max(i, 127); h = Math.min(i, Integer.MAX_VALUE - (-low) -1);的操作。然后分配空间大小为(high - low) + 1。其中Integer.MAX_VALUE为0x7fffffff(2的31次方-1)
/**
* 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);
}
对于普通的Integer使用者貌似不需要关心这些东西,而对于喜欢追求原理的发烧友来说,看源码是一种快乐(需要有功底才可以玩的转啊),源码学习到原理的同时,可以学习到设计思想,同时可以学习别人的编码规范,而且知道自己缺啥,那就使劲补吧。