作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/
import java.util.ArrayList;public class Autoboxing { public static void main(String[] args) {// 手動打包,解決容器類無法放置基礎資料型別 (Elementary Data Type)的問題 Integer intvalue = new Integer(1);//封裝類為參考型別,棧中儲存的是引用,堆上存放實際值 Double doublevalue = new Double(0.5); Float floatvalue = new Float(1.1f); int intVar = intvalue.intValue();//基礎資料型別 (Elementary Data Type)是直接存放在棧上的 double doubleVar = doublevalue.doubleValue(); Float floatVar = floatvalue.floatValue(); System.out.println(intVar +" " + doubleVar +" " +floatVar); ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(intvalue); arr.add(1);//自動封包,將基礎資料型別 (Elementary Data Type)轉為封裝類。 int a = arr.get(0);//自動解包 Integer i = 2;//自動封包 int b = i+2;//自動解包 Integer c=b+2;//自動封包 System.out.println(b); }} 我注意到在specification中有這麼一句,If the value p being boxed is true, false, a byte, a char in the range /u0000 to/u007f, or an int or short number between -128 and 127, then let r1 and r2 bethe results of any two boxing conversions of p. It is always the case that r1 ==r2.也就是說這樣的兩個值在自動封包後r1==r2總返回是ture。
作者:gnuhpc
出處:http://www.cnblogs.com/gnuhpc/