自动装箱拆箱发生在基本类型和其包装型互操作的时候。
以前一直不知的拆箱和装箱是valueOf和xxValue的别名。是语法糖的一种
- publicstaticvoidmain(String[]args){
- Integeri=10;
- Integerj=10;
- System.out.println(j==i);//(1)true
- i=10000;
- j=10000;
- System.out.println(j==i);//(2)false
- i=newInteger(10000);
- System.out.println(i==10000);//(3)true
- System.out.println(10000==i);//(4)true
- System.out.println(i==10000L);//(5)true
- }
(1)处的结果是 true。
(2)处的结果是false。
(3)处的结果是true,true,true
(1),(2)处的结果不同让人惊讶。i = 10;和i=10000;发生了自动装箱,编译器自动编译成 Integer.valueOf(10)和Integer.valueOf(10000)。看看这个方法的实现。
- publicstaticIntegervalueOf(inti){
- if(i>=-128&&i<=IntegerCache.high)
- returnIntegerCache.cache[i+128];
- else
- returnnewInteger(i);
- }
看到某些Integer对象是有缓存的,范围是-128,到high。
再看看IntegerCachestatic final int high;
- staticfinalIntegercache[];
- static{
- finalintlow=-128;
- //highvaluemaybeconfiguredbyproperty
- inth=127;
- if(integerCacheHighPropValue!=null){
- //UseLong.decodeheretoavoidinvokingmethodsthat
- //requireInteger'sautoboxingcachetobeinitialized
- inti=Long.decode(integerCacheHighPropValue).intValue();
- 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++);
- }
high默认是127,可以通过integerCacheHighPropValue
调整,看看这个属性的说明
- /**
- *Cachetosupporttheobjectidentitysemanticsofautoboxingforvaluesbetween
- *-128and127(inclusive)asrequiredbyJLS.
- *
- *Thecacheisinitializedonfirstusage.DuringVMinitializationthe
- *getAndRemoveCachePropertiesmethodmaybeusedtogetandremoveanysystem
- *properitesthatconfigurethecachesize.Atthistime,thesizeofthe
- *cachemaybecontrolledbythevmoption-XX:AutoBoxCacheMax=<size>.
- */
- //valueofjava.lang.Integer.IntegerCache.highproperty(obtainedduringVMinit)
- privatestaticStringintegerCacheHighPropValue;
可以通过该参数调整缓存的范围 -XX:AutoBoxCacheMax=<size>
3,4,5处发生拆箱,编译之后其实调用了intValue,或者longValue。获得的是基本类型。
总结: 两个包装类型的值比较,最好不要用 ==
http://jilen.iteye.com/blog/1189353