java中equals和“==”補充,java中equals補充

來源:互聯網
上載者:User

java中equals和“==”補充,java中equals補充

在JDK1.5之後,Integer添加了自動裝箱,其形式為Integer i = 5;

裝箱過程在記憶體中是  i = new Integer(4);大家都很熟悉這個吧。

當使用這中形式的時候,equals的用法不變,但是“==”略有不同

看下邊的例子:

(1)

Integer x = 12;
Integer y = 12;
System.out.println(x==y);    //true
System.out.println(x.equals(y)); //true

(2)

Integer x = 127;
Integer y = 127;
System.out.println(x==y);    //true
System.out.println(x.equals(y));  //true

結果和(1)相同

(3)

Integer x = 128;
Integer y = 128;
System.out.println(x==y);    //false
System.out.println(x.equals(y)); //true

(4)

Integer x = 129;
Integer y = 129;
System.out.println(x==y);    //false
System.out.println(x.equals(y));  //true

結果和(3)相同

總結:看到equals的用法和在上一篇博文中敘述的相同

但是“==”的用法變了,這是因為,自動裝箱,如果裝箱的是一個位元組方位內的資料(注意上邊的127),那麼這個資料會被共用,不會開闢新的空間,

所以兩個new的地址相同。

聯繫我們

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