一、Java的基础数据类型的包装类:Integer,Long,Double,Float,Boolean,Byte,Short,Character。
二、高频缓存区
-
其中Double和Float没有缓存,其他类型都有高频缓存区间。其高频缓存区间的缓存范围是:
Boolean:使用静态final,就会返回静态值
Byte:-128~127
Short:-128~127
Character:0~127
Long:-128~127
Integer:-128~127 -
如果所使用的包装类的值在这个缓存区间内,就会直接复用已有对象,在缓存区间之外的数值会重新在堆上产生。所以在判断是否相等时不要用“==”,用equals,否则会出现以下情况:
Integer i1 = 127;
Integer i2 = 127;
i1 == i2 ->trueInteger i3 = 128; Integer i4 = 128; i3 == i4 ->false
- Integer是唯一一个可以修改缓存范围的包装类。在VM options加入参数: -XX:AutoBoxCacheMax=555即将缓存区间的最大值改为555. (以上内容属于转载 https://blog.51cto.com/14305934/2432216 以下为扩充)
-
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源码可知设置只能扩大缓存区不能缩小