您的位置:首页 > 编程语言 > Java开发

java基本类型对应包装类的静态缓存

2017-05-25 13:54 288 查看
阅读jdk源码,可以发现,对于基本类型的包装类,是有静态缓存。

1、对Boolean类型,true和false都有对应的缓存,源码为:

/**
* The {@code Boolean} object corresponding to the primitive
* value {@code true}.
*/
public static final Boolean TRUE = new Boolean(true);

/**
* The {@code Boolean} object corresponding to the primitive
* value {@code false}.
*/
public static final Boolean FALSE = new Boolean(false);


2、对于Integer,范围在-128至127内的,都有对应的缓存,源码为:

/**
* 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 -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) {
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)
c7c6
;
}
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() {}
}


3、对于Byte/Short/Long,是和Integer类似的,范围在-128至127内的,都有对应的缓存

总结,对于上述基本类型对应的包装类,只要在缓存范围内,即-128至127范围(一个字节,补码表示的范围)内,

我们是可以直接用=判断相相等的。

4、注意,对于Float和Double类型,并没有对应的缓存。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: