標籤:auto-boxing auto-uboxing
/*JDK5.0新特性:以下的特性適合JDK1.5版本之後的。包括1.5jdk1.4,包括1.4在內之前的所有版本不能使用以下特性。自動裝箱(auto_boxing)和自動拆箱(auto_unboxing)*/public class IntegerTest05{public static void main(String[] args){//JDK5.0之前的.//int-->Integer (裝箱)Integer i1 = new Integer(10);//Integer-->int (拆箱)int i2 = i1.intValue();//JDK5.0之後,包括5.0Integer i3 = 10; //自動裝箱int i4 = i3; //自動拆箱System.out.println(i3); //"10"System.out.println(i4+1); //11//JDK5.0之後m1(321); //自動裝箱.System.out.println(m2(10,5) + 1); //自動裝箱}public static void m1(Object o){System.out.println(o);}public static int m2(Integer i1,Integer i2){return i1 - i2; //自動拆箱}}//深入瞭解自動裝箱和自動拆箱/*深入自動裝箱和自動拆箱:1.自動裝箱和自動拆箱是程式編譯階段的一個概念,和程式運行無關。2.自動裝箱和自動拆箱主要目的是方便程式員編碼。*/public class IntegerTest06{public static void main(String[] args){Integer i1 = new Integer(10);Integer i2 = new Integer(10);//這裡不會有自動拆箱System.out.println(i1==i2); //false//比較兩個Integer類型的資料是否相等,不能用"=="//Integer已經重寫了Object中的equals方法.System.out.println(i1.equals(i2)); //true//重點:Integer i3 = 128;Integer i4 = 128;//上面的等同於//Integer i3 = new Integer(128);//Integer i4 = new Integer(128);System.out.println(i3==i4); //false//注意以下程式.//如果資料是在(-128~127)之間,java中引入了一個“整型常量池”,在方法區中。//該整型常量池只儲存-128~127之間的資料。Integer i5 = 127; //這個程式不會在堆中建立對象,會直接從整型常量池中拿.Integer i6 = 127;System.out.println(i5==i6); //trueInteger i7 = -128;Integer i8 = -128;System.out.println(i7==i8); //trueInteger i9 = -129;Integer i10 = -129;System.out.println(i9==i10); //false}}
本文出自 “gaogaozi” 部落格,請務必保留此出處http://hangtiangazi.blog.51cto.com/8584103/1662493
java中的自動裝箱和自動拆箱