【Java學習筆記】自動封包和解包(Autoboxing和AutoUnboxing)

來源:互聯網
上載者:User

作者: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/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.