Java拆装箱深度剖析
先来看一段代码:
publicclassMain{
publicstaticvoidmain(String[]args){
Integernum1=100;
Integernum2=100;
Integernum3=200;
Integernum4=200;
'''//输出结果'''
System.out.println(num1==num2);
System.out.println(num3==num4);
}
}
猜猜结果是什么?
很多人都会认为结果全为true,但结果去不是这样的
true
false
为什么是这样的结果?如果用内存来解释结果的话,num1和num2指向的是同一个对象,而num3和num4则指向的确是不同的对象。接下来就告诉你为什么,看一看Integer类型的valueof方法的源码:
publicstaticIntegervalueOf(inti){
assertIntegerCache.high>=127;
if(i>=IntegerCache.low&&i<=IntegerCache.high)
returnIntegerCache.cache[i+128];
returnnewInteger(i);
}
其中IntegerCache的实现:
'''//IntegerCache,一个内部类,注意它的属性都是定义为staticfinal'''
privatestaticclassIntegerCache{
staticfinalinthigh;'''//缓存上界,暂为null'''
staticfinalIntegercache[];'''//缓存的整型数组'''
'''//块,为什么定义为块'''
static{
finalintlow=-128;'''//缓存下界,不可变了。只有上界可以改变'''
'''//highvaluemaybeconfiguredbyproperty'''
'''//h值,可以通过设置jdk的AutoBoxCacheMax参数调整(以下有解释),自动缓存区间设置为[-128,N]。注意区间的下界是固定'''
inth=127;
if(integerCacheHighPropValue!=null){
'''//UseLong.decodeheretoavoidinvokingmethodsthat'''
'''//requireInteger'sautoboxingcachetobeinitialized'''
//通过解码integerCacheHighPropValue,而得到一个候选的上界值'''
inti=Long.decode(integerCacheHighPropValue).intValue();
'''//取较大的作为上界,但又不能大于Integer的边界MAX_VALUE'''
i=Math.max(i,127);
'''//MaximumarraysizeisInteger.MAX_VALUE'''
h=Math.min(i,Integer.MAX_VALUE--low);
}
high=h;'''//上界确定'''
'''//就可以创建缓存块,注意缓存数组大小'''
cache=newInteger[(high-low)+1];//
intj=low;
for(intk=0;k<cache.length;k++)
cache[k]=newInteger(j++);'''//-128到high值逐一分配到缓存数组'''
}
privateIntegerCache(){}
}
通过这两段代码可以看出,在通过valueof方法创建Integer类型对象时,取值范围为[-128,127],数值在这个区间里,指针指向IntegerCache.cache中已经存在的对象引用,当数值超出这个范围,就会创建一个新的对象。
有一点需要注意的是,并不是所有的类型都是这个范围,看Double类型:
publicclassMain{
publicstaticvoidmain(String[]args){
Doublei1=100.0;
Doublei2=100.0;
Doublei3=200.0;
Doublei4=200.0;
System.out.println(i1==i2);
System.out.println(i3==i4);
}
}
最终的输出结果:
false
false
具体为什么回事这样的结果,大伙可以去看看源代码中Doublevalueof方法的实现,其和Integervalueof方法不同,是因为在某个范围内的整型数值的个数是有限的,而浮点数却不是。
注意,Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。
Double、Float的valueOf方法的实现是类似的。
拉下了一个,Boolean类型的结果有两个TrueorFalse。直接看源代码:
publicstaticBooleanvalueOf(booleanb){
return(b?TRUE:FALSE);
}
而其中的TRUE和FALSE是这样定义的:
publicstaticfinalBooleanTRUE=newBoolean(true); '''/**''' '''*The<code>Boolean</code>objectcorrespondingtotheprimitive''' '''*value<code>false</code>.''' '''*/''' publicstaticfinalBooleanFALSE=newBoolean(false);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。