Java自动装箱和自动拆箱
1 自动装箱和自动拆箱
自动装箱:
允许将一个基本类型数据直接赋值给一个它对应的包装类变量。
自动拆箱:
允许将一个包装类变量直接赋值给它对象的基本类型变量。
例子:
在jdk1.5直接基本数据类型和其包装类的转换必须用new Constructor()和WrapperClassInstance.xxxValue()。如下:
2 包装类还可以实现基本类型和字符串之间的转换
字符串向基本类型转换:
- 通过WrapperClass.parseXXX(String str)(出Character包装类其他包装类都提供了)
- 通过new WrapperClass(String str)的构造函数
基本类型向字符串转换:
通过String.valueOf()方法
3 包装类可以与基本类型比较
这种比较是取出包装类实例所包装的基本类型的数值进行比较的。
4 一个容易出错的情况
public class Main {
public static void main(String[] args) {
Integer a=3;
Integer b=3;
Integer e=new Integer(3);
Integer c=199;
Integer d=199;
System.out.println(a==b);//
System.out.println(3==e);//与包装类比较是取出包装类实例的基本类型值进行比较的
System.out.println(b.equals(e));//两个不同对象实例
System.out.println(c==d);//-128到127的都已经被存到cache里面了
}
}
输出结果:
为什么a==b为true,c==d为false呢?
原因是这样的
系统先把-128-127的数自动装箱到cache中,以后发生自动装箱时,如果基本类型的值是-128到127之间,它就指向cache数值里面的对象。所以a==b为true,c==d为false。
Integer,Short,Byte,Long,Boolean都实现了这种缓存机制。
public static void main(String[] args) {
System.out.println("int");
Integer a=3;
Integer b=3;
Integer e=new Integer(3);
Integer c=199;
Integer d=199;
//Byte,Short,Long与Integer一样保存了-128-127的对象
System.out.println(a==b);//
System.out.println(3==e);//与包装类比较是取出包装类实例的基本类型值进行比较的
System.out.println(b.equals(e));//两个不同对象实例
System.out.println(c==d);//-128到127的都已经被存到cache里面了
//double,float,char就没有实现
System.out.println("double");
Double da=3.0;
Double db=3.0;
System.out.println(da==db);
//Boolean也是把true和false自动装箱了,并保持到两个静态变量中了
System.out.println("boolean");
Boolean ba=true;
Boolean bb=true;
System.out.println(ba=bb);
}