java中自动打包 解包机制(又称自动装箱,拆箱)Auto-Boxing,UnBoxing
JDK 1.5以后引入了不少概念
Boxing Unboxing(装箱 拆箱 有人译作打包解包)还有Generic(泛型) 这些概念和 C# 有着惊人的相似。
这里的装箱应该理解为 封装对象 ,即把基础数据类型(如 int)转换成基础类型封装类的对象(如 new Integer())
拆箱就是装箱的反过程,即把基础类型封装类的对象(如 new Integer())转换为基础数据类型(如 int)。
装箱: Integer a = new Integer() ; a = 100 ;拆箱: int b = new Integer(100) ;
Object myObject = 100; //Boxing + Upcastingint i = (Integer) myObject; //Unboxing + Downcasting第一行是先把int类型的100装箱为Integer对象 然后上塑造型 为Object类型 赋值给 myObject
Class a = new Class(parameter);
Integer i = 100; (注意:不是 int i = 100; )
eg: int t = 1; t. 后面是没有方法滴。 Integer t =1; t. 后面就有很多方法可让你调用了。??什么时候自动装箱
1 Integer i = 10; //装箱 2 int t = i; //拆箱
1 Integer i = 10; 2 System.out.println(i++);
??Integer的自动装箱 //在-128~127 之外的数 Integer i1 = 200; Integer i2 = 200; System.out.println("i1==i2: "+(i1==i2)); // 在-128~127 之内的数 Integer i3 = 100; Integer i4 = 100; System.out.println("i3==i4: "+(i3==i4)); 输出的结果是: i1==i2: false i3==i4: true
1 Integer i3 = new Integer(100); 2 Integer i4 = new Integer(100); 3 System.out.println("i3==i4: "+(i3==i4));//显示false
1 String str1 = "abc";2 String str2 = "abc";3 System.out.println(str2==str1); //输出为 true 4 System.out.println(str2.equals(str1)); //输出为 true 5 6 String str3 = new String("abc");7 String str4 = new String("abc"); 8 System.out.println(str3==str4); //输出为 false 9 System.out.println(str3.equals(str4)); //输出为 true
1 String d ="2"; 2 String e = "23";3 e = e.substring(0, 1);4 System.out.println(e.equals(d)); //输出为 true 5 System.out.println(e==d); //输出为 false