java參考型別和基本類型的比較

來源:互聯網
上載者:User

參考型別和基本類型的分類,不在寫了,網上有很多。

我們知道:
當兩個基本類型使用”==”比較時,他們比較的是值。
當兩個參考型別使用”==”比較時,他們比較的是地址。
當兩個參考型別使用方法equals()比較時,他們比較的是值。

但當基本類型和他的封裝類(參考型別)使用”==”比較時,
他們的結果又是如何呢。

下面我們使用Integer和int進行說明。
Integer是int的封裝類。 int 基本類型, Integer 為參考型別。
看個例子:

int i = 1234;Integer i1 = new Integer(1234);Integer i2 = new Integer(1234);System.out.print("i1 == i2 : "+(i1 == i2));System.out.println("\ti1.equals(i2) : "+(i1.equals(i2)));System.out.print("i == i1 : "+(i == i1));System.out.println("\t\ti1.equals(i) : "+(i1.equals(i)));System.out.print("i == i2 : "+(i == i2));System.out.println("\t\ti2.equals(i) : "+(i2.equals(i)));

列印:
i1 == i2 : false i1.equals(i2) : true
i == i1 : true i1.equals(i) : true
i == i2 : true i2.equals(i) : true

我們可以看到 i == i1, i == i2, i1 != i2,
但使用equals()他們都是相等的。

接著我們來看看jdk1.8中Integer類中的方法equals()

    public boolean equals(Object obj) {        if (obj instanceof Integer) {            return value == ((Integer)obj).intValue();        }        return false;    }

可以觀察到使用equals(),他們比較的是值。

總結:當比較基本類型和他的封裝類(參考型別)使用”==”和方法equals()比較時,他們比較的都是值。

Integer和其它基本類型都相同,大家有興趣可以去證明,在此我都不在寫了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.