现在的位置: 首页 > 综合 > 正文

自动装箱与拆箱引发的享元设计模式

2013年08月13日 ⁄ 综合 ⁄ 共 876字 ⁄ 字号 评论关闭
/**
 * 自动装箱与拆箱
 */
public class Autoboxing {

	public static void main(String[] args) {
		Integer num1 = 20;			//自动装箱
		int num2 = new Integer(20);		//自动拆箱
		System.out.println(num2 == num1);	//true
		
		//-128~127之间的同一个Intege对象相比为true
		Integer num3 = 128;
		Integer num4 = 128;
		System.out.println(num3 == num4);	//false
		
		Integer num5 = -129;
		Integer num6 = -129;
		System.out.println(num5 == num6);	//false
	}
}

代码说明:

Integer num1 = 20;自动将int类型的整数20转换一个Integer对象,赋给num1;(装箱)

int num2 = new Integer(20);  自动将Integer对象的值20转换成int类型(拆箱)

在JDK5.0之前,这种方式是不能通过编译的,比如上述示例在JDK1.4只能通过new的方式创建Integer对象。

由自动装箱与拆箱引发的享元模式:

//存储-128~127之间的Integer对象
Integer num3 = 128;
Integer num4 = 128;
System.out.println(num3 == num4);	//false
		
Integer num5 = -129;
Integer num6 = -129;
System.out.println(num5 == num6);	//false

因为较小的整数用的频率比较广泛,所以JAVA虚拟机启动后将-128~127之间整数对像缓存起来,这样每次在使用-128~127之间的整数对象时不用频繁的创建,而是直接去缓存池里取,如果缓存池里存在该数值,就直接取出来,如果不存在,则创建一新的对象返回,这样一来即可节省内存资源。这种将常用或公共的数据缓存起来反复复用的方式,叫做享元模式。

以上只是个人的见解,如有不正确的地方,请前辈指教!

抱歉!评论已关闭.