首頁  >  問答  >  主體

Java基本型別作為局部變數和成員變數時的儲存方式有何不同?

1、這個問題可能牽涉到很多方面,我自己研究了一下,弄清楚了一部分,但是有一部分還​​不清楚。先貼程式碼(Java版本1.8):

public class Test{
    int abc1 = 127;
    Integer abd1 = 127;
    Integer abf1 = 127;
    Integer abe1 = new Integer(127);
    {
        System.out.print("1\t");
        System.out.println(abc1==abd1);
        System.out.print("2\t");
        System.out.println(abd1==abe1);
        System.out.print("3\t");
        System.out.println(abc1==abe1);
        System.out.print("4\t");
        System.out.println(abd1==abf1);
    }

    int abc2 = 128;
    Integer abd2 = 128;
    Integer abf2 = 128;
    Integer abe2 = new Integer(128);
    {
        System.out.print("5\t");
        System.out.println(abc2==abd2);
        System.out.print("6\t");
        System.out.println(abd2==abe2);
        System.out.print("7\t");
        System.out.println(abc2==abe2);
        System.out.print("8\t");
        System.out.println(abd2==abf2);
    }

    public static void main(String[] args){
        Test t =new Test();
    }
/*输出为:
1       true
2       false
3       true
4       true
5       true
6       false
7       true
8       false
*/
}

2、先說自己清楚的部分:第4個輸出與第8個輸出比較清楚。這是由於在Java堆中有一個用於儲存 常用基本資料型別字面量 的常數池,這個常數池可以儲存整數(-128到127),布林類型(沒有double型別)。執行「Integer abd1=127」時,除了在堆中建立一個值為127的Integer物件外,還會在對應的常數池中儲存一個127,然後,將這個Integer物件與常數池中的127關聯起來;再執行「Integer abf1=127」時,除了建立物件外,同樣將其與常數池中的127關聯起來,因而比較二者回傳的是true。 128就不同了,由於超出了常數池的儲存範圍,比較的只是兩個Integer引用i1與i2,所以回傳的是false。

3、我的問題是:物件成員變數中的int型別(非static,非final)是怎麼儲存的。也就是說,當新建一個Text物件t時,abc1(abc2與此類似)是直接存在棧裡還是包裝後存在堆裡,為什麼會出現1-3(或5-7)回傳是「true,false, true」的情況。

世界只因有你世界只因有你2702 天前548

全部回覆(1)我來回復

  • 给我你的怀抱

    给我你的怀抱2017-05-27 17:43:41

    一int和Integer比較時,Integer會自動拆箱後與int比較
    二物件實例變數分配在堆上
    1和5比較由於Integer類型自動拆箱所以為true
    new Integer(xxx) xxx即使在緩存範圍之內也會建立新的物件所以2是false

    回覆
    0
  • 取消回覆