Integer 和Int的區別+new Integer和int值比較的問題

Integer 和Int的區別

Integer是包裝類,|  需要實例化才能用,|  默認值是null,|  存的是對象的引用。

Int是基礎數據類型,|  直接可以用,     |   默認值是0,     |  直接存數據。

 

Integer 和int 的==比較

//數值範圍在-128到127之間時。
        int d = 100;
        Integer a = 100;
        Integer b = 100;
        Integer c = new Integer(100);
        System.out.println(a == b);  //true
        System.out.println(a == c);  // false
        System.out.println(a == d);  //true

        //範圍不在-128到127之間的int
        int aa = 200;
        int bb = 200;
        Integer cc = new Integer(200);
        System.out.println(aa == bb);  //true 
        System.out.println(aa == cc); //false

        //範圍不在-128到127之間的Integer
        Integer aaa = 200;
        Integer bbb = 200;
        System.out.println(aaa == bbb);  //false 
        System.out.println(aa == aaa);  //true integer和int比,會自動拆箱,比較值的大小

int和int可以直接比較(==),雖然==比的是地址,但那是針對包裝類型(也就是new出來的類型而言的),而int是基礎類型,所以比較的是值的大小,沒有-128至127的限制。

Integer 和int的值相互比較的時候(==),比較的是值的大小,因爲integer會自動拆箱,

Integer i=127Integer j=127相互比較的時候(==),是相等的;

Integer i=128Integer j=128相互比較的時候(==),是不等的;

因爲JVM會自動維護八種基本類型的常量池,int常量池中初始化-128~127的範圍,所以當爲Integer i=127時,

在自動裝箱過程中是取自常量池中的數值,而當Integer i=128時,128不在常量池範圍內,

所以在自動裝箱過程中需new 128,所以地址不一樣。

 

equals 和==的比較比較麻煩

Integer重寫了equals,比較的是值,類似的string也是比較的值。

而== 比較的是地址。

public class IntegerTest {
    public static void main(String[] args) {


        Integer a = 1;
        Integer d = 1;
        int b = 1;
        Integer c = new Integer(1);
        System.out.println(a == b);  //True,自動拆箱裝箱,比的是值
        System.out.println(a == c); // false ==比的是地址,不是一個對象。
        System.out.println(a == d); // True a 和d是一個對象?
        System.out.println(b == c); //True Integer自動拆箱,比的值
        System.out.println(a.equals(c)); //True
        System.out.println(a.equals(b)); //True Integer重寫了equals,比較的是值
        System.out.println(b.equals(c));  //這句是錯誤的,因爲int類型的b沒有equals方法。
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章