欢迎来到天天文库
浏览记录
ID:51583097
大小:43.52 KB
页数:4页
时间:2020-03-13
《java自动装箱拆箱总结.doc》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、java自动装箱拆箱总结对于java1.5引入的自动装箱拆箱,之前只是知道一点点,最近在看一篇博客时发现自己对自动装箱拆箱这个特性了解的太少了,所以今天研究了下这个特性。以下是结合测试代码进行的总结。测试代码:inta=1;Integerb=1;Integerc=1;Integerd=2;Integere=3;Integerf=128;Integerg=128;Longh=3L;Doublem=4.0;Doublen=4.0;Floatp=5f;Floatq=5f;System.out.println("a==b:"+(a==b
2、));//trueSystem.out.println("b==c:"+(b==c));//trueSystem.out.println("e==(c+d):"+(e==(c+d)));//trueSystem.out.println("e.equals(c+d):"+(e.equals(c+d)));//trueSystem.out.println("h==(c+d):"+(h==(c+d)));//trueSystem.out.println("h.equals(c+d):"+(h.equals(c+d)));//false
3、System.out.println("f==g:"+(f==g));//falseSystem.out.println("m==n:"+(m==n));//falseSystem.out.println("p==q:"+(p==q));//falseSystem.out.println("m==d*2:"+(m==d*2));//trueSystem.out.println("p==(d+e):"+(p==(d+e)));//true测试输出结果与说明:1.a==b:true当基本类型包装类与基本类型值进行==运算时,包装类会
4、自动拆箱。即比较的是基本类型值。具体实现上,是调用了Integer.intValue()方法实现拆箱。可以在测试代码处打断点,使用F5快捷键stepinto至每一步执行方法,会看到调用了Integer.intValue()方法实现了拆箱。2.b==c:trueb和c类型均为Integer包装类,故对基本类型进行自动装箱后赋值给b和c。在进行==运算时不会触发拆箱操作。所以比较的是引用地址,说明b和c是同一个对象。java中自动装箱调用的是Integer.valueOf()方法实现的,可以像例1一样打断点验证。为什么b和c会是同一
5、个对象呢?查看Integer.valueOf()方法实现即可知道,如下:下面的代码中可以看到,对于-128至127这256个值,直接获取的IntegerCache中的值。而IntegerCache是Integer中的一个静态内部类,里面将-128至127(即一个字节所能表示的所有带符号值-2^7至2^7-1)的包装类存在了一个数组中。对于-128到127之间的数,直接从数组中获取,其他的数则使用new生成。所以此处输出true。publicstaticIntegervalueOf(inti){if(i>=-128&&i<=Int
6、egerCache.high)returnIntegerCache.cache[i+128];elsereturnnewInteger(i);}privatestaticclassIntegerCache{staticfinalinthigh;staticfinalIntegercache[];static{finalintlow=-128;//highvaluemaybeconfiguredbypropertyinth=127;if(integerCacheHighPropValue!=null){//UseLong.deco
7、deheretoavoidinvokingmethodsthat//requireInteger'sautoboxingcachetobeinitializedinti=Long.decode(integerCacheHighPropValue).intValue();i=Math.max(i,127);//MaximumarraysizeisInteger.MAX_VALUEh=Math.min(i,Integer.MAX_VALUE--low);}high=h;cache=newInteger[(high-low)+1];i
8、ntj=low;for(intk=0;k
此文档下载收益归作者所有