自动装箱,拆箱
参考:http://www.cnblogs.com/danne823/archive/2011/04/22/2025332.html
Java包装类,Wrapper~~由于在java中,数据类型总共分为两大类,基本数据类型(值类型)和类类型(引用数据类型)。基本数据类型的数据不是对象,所以对于要将数据类型作为对象来使用的情况,java提供了相对应的包装类。
所谓自动装箱,自动拆箱
基本数据类型的自动装箱(autoboxing)、自动拆箱(unboxing)是自J2SE 5.0开始提供的功能。
一般我们要创建一个类的对象实例的时候我们会这样:
Class a = new Class (Parameter);
当我们创建一个Integer对象时,却可以这样: Integer i = 100;
实际上,执行上面那句代码的时候,系统为我们Integer i = Integer.valueOf(100);
此即为基本数据类型的自动装箱功能。
什么是自动装箱?
例如:`Integer i = 100`;相当于编译器自动执行 `Integer i = Integer.valueOf(100);`
什么是自动拆箱?
自动拆箱,也就是将对象中的基本数据从对象中自动取出。如下就实现自动拆箱:
Integer i = 10;//实现自动装箱
int t = i;//实现自动拆箱,实际上执行 int t = i.intValue();
自动拆箱(unboxing),也就是将对象中的基本数据从对象中自动取出。如下可实现自动拆箱:
Integer i = 10;
System.out.println(i++);
Integer自动装箱
说明:equals()比较的是两个对象的值(内容)是否相同。”==”比较的是两个对象的引用(内存地址)是否相同。也用来比较两个基本数据类型的变量值是否相等。
//在-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
对于输出结果的源码解释应该先看Integer.java的源码。
前面说过,int 的自动装箱,是系统执行了 Integer.valueOf(int i)
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high) // 没有设置的话,IngegerCache.high 默认是127
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
源码解析:对于–128到127(默认是127)之间的值,Integer.valueOf(int i) 返回的是缓存的Integer对象(并不是新建对象)所以范例中,i3 与 i4实际上是指向同一个对象。而其他值,执行Integer.valueOf(int i) 返回的是一个新建的 Integer对象,所以范例中,i1与i2 指向的是不同的对象。
String自动装箱
先看例子:
String str1 ="abc";
String str2 ="abc";
System.out.println(str2==str1); //输出为 true
System.out.println(str2.equals(str1)); //输出为 true
String str3 =new String("abc");
String str4 =new String("abc");
System.out.println(str3==str4); //输出为 false
System.out.println(str3.equals(str4)); //输出为 true
对于上面的例子应该是很好理解的。str1与str2拥有相同的内存地址,为同一个引用。因此无论书”==”还是equals.都应该返回true。而对于str3和str4是重新new出来的新对象,因此肯定拥有的不同 的内存地址,因此此时”==”为false,但是因为两者之间存储内容一致,所以equals返回true。
String d ="2";
String e ="23";
e = e.substring(0, 1);
System.out.println(e.equals(d)); //输出为 true
System.out.println(e==d); //输出为 false
e和d的初始化值不一致,因此e和d是两个不同的对象。拥有不同的内存地址,故有”==”为false,equals返回true。