自动装箱和自动拆箱

JDK5的新特性
  • 自动装箱: 把基本数据类型转化为包装类类型
  • 自动拆箱: 把包装类类型转化为基本数据类型
package com.mephisto.wrapclass;

public class Demo3 {

	public static void main(String[] args) {
/*		int x = 100;
		Integer i1 = new Integer(x);	// 将基本数据类型包装成对象, 装箱
		
		int y = i1.intValue();			// 将对象转化为基本数据类型, 拆箱
*/		
		Integer i2 = 100;			// 自动装箱, 把基本数据类型转化成对象
		int z = i2 + 200;			// 自动拆箱, 把对象转化成基本数据类型
		System.out.println(z);		// 300
		
       	Integer i3 = null;
		int a = i3  + 100;			// 底层用i3调用的intalue, 但是i3是null, null调用方法就会出现
		System.out.println(a);		//	空指针异常 java.lang.NullPointerException
	}
}

实例
package com.mephisto.wrapclass;

import java.lang.Integer.IntegerCache;

public class Demo4 {
	
	public static void main(String[] args) {
		Integer i1 = new Integer(97);
		Integer i2 = new Integer(97);
		System.out.println(i1 == i2);				// flase
		System.out.println(i1.equals(i2));			// true
		System.out.println("================");
		
		
		
		Integer i3 = new Integer(197);
		Integer i4 = new Integer(197);	
		System.out.println(i3 == i4);				// flase
		System.out.println(i3.equals(i4));			// true
		System.out.println("================");
		
		/* -128 到 127是byte的范围, 如果在这个取值范围内,自动装箱就不会新创建对象, 而是
		 * 从常量池中获取
		 * 否则, 重新创建
		 */
		/*

		public static Integer valueOf(int i) {
	        if (i >= IntegerCache.low && i <= IntegerCache.high)		// i >= -128 && i <= 127
	            return IntegerCache.cache[i + (-IntegerCache.low)];  
	        return new Integer(i);
	    }

		 */
		
		Integer i5 = 97;
		Integer i6 = 97;
		System.out.println(i5 == i6);				// true
		System.out.println(i5.equals(i6));
		System.out.println("================");		// true
		
		
		Integer i7 = 197;
		Integer i8 = 197;
		System.out.println(i7 == i8);				// flase
		System.out.println(i7.equals(i8));			// true	
		System.out.println("================");
	}

}
posted @ 2018-08-06 17:53  无聊的子木君  阅读(141)  评论(0编辑  收藏  举报