我就来说说基本类型包装类的valueOf吧,下面用Integer为例:
/*1*///true
Integer i1 = Integer.valueOf(1);
Integer i2 = Integer.valueOf(1);
System.out.println(i1==i2);
/*2*///false
i1 = new Integer(1);
i2 = new Integer(1);
System.out.println(i1==i2);
/*3*///false
i1 = new Integer(1);
i2 = Integer.valueOf(1);
System.out.println(i1==i2);
//了解过自动拆箱和装箱的同学都知道 Integer i = 1 其实就等同于 Integer i = Integer.valueOf(1);所以只有这三种
其实我是查阅了源码才有根本上的理解的,如下:
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
......
}
代码的意思是显而易见的cache是Integer类型的数组,cache本身就是缓存的意思,所以valueOf就是在指定范围内返回cache缓存中的值,超出范围则new一个,若当1存在于缓存cache中,上文的3个结果也就明了了IntegerCache.low==-128我们都知道了,下面我去深究下IntegerCache.high到底有多大,源码附上:
static {
// high value may be configured by property
int h = 127;-------------------------------------------------------------------1
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;-----------------------------------------------------------------------2
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;
}
这是IntegerCache中的静态代码块,在类加载的时候执行一次,我们直接看---1和---2处,中间代码不管,整个结构就只是给high赋值,循环建立从low到high大小的cache缓存数组,很简单吧,下面再看看1---2中间部分,我用注释的方式写出:
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");//读取javaInteger缓存最大值配置,默认127
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127); //若自行配制的最大值小于127,就取127
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
//这是Integer前面定义的常量public static final int MAX_VALUE = 0x7fffffff;
//若自行配制的最大值上限还是有限制的最大为:Integer.MAX_VALUE - (-low) -1
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
assert IntegerCache.high >= 127; //断言函数,自行百度
最后: -D可以设置java.lang.Integer.IntegerCache.high
谢阅