您的位置:首页 > 其它

64_常用类_自动装箱和拆箱_缓存处理

2017-06-15 14:26 295 查看

自动装箱和拆箱(aotu-boxing & unboxing)

就是将基本类型和包装类进行自动的互相转换。

JDK5.0后,将自动装箱/拆箱引入java中。

自动装箱的过程:每当需要一种类型的对象时,这种基本类型就自动地封装到与它相同类型的包装中。

自动拆箱的过程:每当需要一个值时,被装箱对象中的值就被自动地提取出来,没必要再去调用intValue()和doubleValue()方法。

Integer i = null;
int j = i;
//这样的语法在编译时期是合法的,但是在运行时期会有错误,因为这种写法相当于:
Integer i = null;
int j = i.intValue();
//null表示i没有参考至任何的对象实体,它可以合法地指定给对象参考名称。由于实际上i并没有参考至任何的对象,所以也就不可能操作intValue()方法,这样上面的写法在运行时会出现NullPointerException错误。


public class AutoBoxing {
public static void main(String[] args) {
//Integer i= new Integer(100);
Integer i=100;//jdk5.0之后,编译器帮我们改进代码相当于Integer i1=new Integer(100);
Integer i2=2000;
int c=i2;//自动拆箱,编译器帮我们改进:i2.intValue();
System.out.println(c);
//缓存问题
Integer d=1234;
Integer d2=1234;
System.out.println(d==d2);//false
System.out.println(d.equals(d2));//true
System.out.println("*******************");
Integer d3=-129;//[-128,127]之间的数,仍然当做基本数据类型来处理。
Integer d4=-129;
System.out.println(d3==d4);
System.out.println(d3.equals(d4));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: