自动装箱 和 自动拆箱

自动装箱 auto-boxing

基本类型就自动地封装到与它相同类型的包装中,如:

Integer i= 100;

本质上是,编译器编译时为我们添加了:

Integer i = new Integer(100);

自动拆箱 unboxing:

包装类对象自动转换成基本类型数据,如:

int a = new Integer(100);

本质上,编译器编译时为我们添加了:

int a = new Integer(100).intValue();

缓存问题

intValue就是把Integer类型转化为int类型

/**
 * 测试自动装箱和自动拆箱
 * (加了代码而已)
 * @author Administrator
 *
 */
public class Test02 {
	public static void main(String[] args) {
		//自动装箱
		//现在可以不用这样写,编译器会自动帮你生成   原: Integer a = new Integer(100);
		Integer a = 1000;
		Integer b = 2000;
		
		//自动拆箱
		//编译器自动改进:int c = new Integer(1500).intValue();
		int c = new Integer(1500);
		Integer d = 2000;
		int e = d;//编译器改进:d.intValue();
		System.out.println(e);
		
		Integer d1 = 1234;
		Integer d2 = 1234;
		System.out.println(d1==d2);
		System.out.println(d1.equals(d2));
		
		System.out.println("****************************");
		
		//属于[-128,127]之间的数,仍然当做基本数据类型来处理
		Integer d3 = 123;
		Integer d4 = 123;
		System.out.println(d3==d4);
		System.out.println(d3.equals(d4));
		
		System.out.println("****************************");
		Integer d5 = 128;
		Integer d6 = 128;
		System.out.println(d5==d6);
		System.out.println(d5.equals(d6));
		
	}
}

结果显示:
2000
false
true
****************************
true
true
****************************
false
true

猜你喜欢

转载自blog.csdn.net/szlg510027010/article/details/81479017