1. 程式人生 > >自動裝箱和拆箱(包裝和解包)

自動裝箱和拆箱(包裝和解包)

自動裝箱:就是把基礎資料型別自動封裝並轉換成對應的包裝類的對象。
拆 箱 :就是把包裝類的物件自動解包並轉換成對應的基礎資料型別。

public class BoxDemo {

    public static void main(String[] args) {
        //demo1();
        demo2();

    }
    private static void demo2() {
        //Integer型別的自動裝箱細節:一個位元組範圍內的整數(-128~127),是把值直接放在棧中的。一個位元組範圍以外的資料是放在堆中的,棧中放的是地址
Integer a1 = 100; Integer a2 = 100; System.out.println(a1==a2);//true Integer a3 = 200; Integer a4 = 200; System.out.println(a3==a4);//false Integer a5 = 100;//是裝箱,且資料範圍在一個位元組之內,資料放在棧中 Integer a6 = new Integer(100);//顯式new的,資料是在堆中開的---不是裝箱 System.out
.println(a5==a6);//false System.out.println("================"); //Integer型別物件如果和一個具體的數值比較,那麼會自動拆箱(把其中的值取出來) 再和數值比較 Integer a7 = new Integer(200); Integer a8 = 200; System.out.println(a7==200);//true System.out.println(a8==200);//true } private static void demo1
() { Integer a1 = 100; //自動裝箱 ---把基本資料型別的資料直接賦給一個包裝類物件(引用),Java自動幫我們封裝成一個物件 System.out.println("a1="+a1); Integer a2 = new Integer(100); int i = a2;//自動拆箱 System.out.println("i="+i); System.out.println(a1==a2);//false System.out.println(a1==100);//true System.out.println(a1==i);//true System.out.println("============"); System.out.println(a1.hashCode()); System.out.println(a2.hashCode()); } }
public class BoxDemo2 {

    public static void main(String[] args) {
        String str1 = "abc";
        String str2 = "abc";
        System.out.println(str1==str2); //true
        System.out.println( str1.equals(str2) );//true

        System.out.println("============");

        String str3 = new String("abc"); //只要一new就在堆中新開一塊記憶體空間
        String str4 = new String("abc");
        System.out.println(str3==str4); //false
        System.out.println( str3.equals(str4) );//true

        System.out.println("============");
        System.out.println(str1==str3); //false
        System.out.println(str1=="abc");//true   拆箱後再比較---把具體的資料取出來比較
        System.out.println(str3=="abc");//false  str3本身就是顯式new出來,不存在拆箱問題,因此直接拿棧中的資料去比較


        //總之,以後要比較字串的內容是否相等,
        //一定用 str.equals() 或 str.equalsIgnoreCase()

        //※String類中的所有字串處理方法,都不會在原物件上修改,而是返回一個新物件。
        //※因此凡是String型變數(物件),無論是不是new出來,判斷"=="都是使用基本資料型別的用法,即判斷棧中的資料 ---傳參也一樣,可以直接理解成值傳遞

        String s="2";
        String s2="23";
        s2=s2.substring(0, 1);//返回的是一個新new的String物件
        System.out.println(s==s2);//false
        System.out.println(s.equals(s2));

        String ss = "abc";
        aa(ss);
        System.out.println("ss: "+ss);
        String ss2 = new String("abc");
        aa(ss2);
        System.out.println("ss2: "+ss2);


        String sss="aa"+"bb"+"cc"+"dd"; //StringBuffer StringBuilder
    }

    public static void aa(String str){
        str=str+"ok";
    }

}