java-基礎入門-自動裝箱與自動拆箱留給我們的坑

來源:互聯網
上載者:User

標籤:源碼   對象   編譯器   緩衝   坑   

其實,java在自動裝箱和自動拆箱的過程裡面,留了不少的坑給我們,我們下面將以integer這個類為基礎討論一下

其實這裡面主要涉及的是兩點

1.當使用Integer x=1,這樣的方式來賦值的時候,其實,編譯器當那個1是String,然後需要通過valueof的方法轉換過來,但是在轉換的過程中,他為了最佳化速度,使用了我們所不知道的緩衝,因為在這裡會出現一些坑

2.Integer類裡面重寫了equals方法,裡面不但對比對象,而且還對比裡面的值


下面先上代碼:(請仔細觀看注釋,裡面已經提供了上面所述兩個方法的源碼)

package com.ray.object;/** * 自動裝箱與自動拆箱的坑 *  * @author ray * @since 2015-05-04 * @version 1.0 *  */public class Test {public static void main(String[] args) {// 其實下面這幾句後面的賦值1,1,1000,1000,都被當做是string,// 然後通過Integer.valueOf()這個方法轉換過來,// 我們下面來看看Integer.valueOf()這個方法的源碼// public static Integer valueOf(int i) {// if(i >= -128 && i <= IntegerCache.high)// return IntegerCache.cache[i + 128];// else// return new Integer(i);// }// 在源碼裡面其實是緩衝了一部分資料,是-128-127// 因此,在a==b是返回true// c==d是返回falseInteger a = 1;Integer b = 1;Integer c = 1000;Integer d = 1000;System.out.println("a == b ---- " + (a == b));// trueSystem.out.println("c == d ---- " + (c == d));// false// 這下面是構造4個integer的對象出來Integer a_1 = new Integer(1);Integer b_1 = new Integer(1);Integer c_1 = new Integer(1000);Integer d_1 = new Integer(1000);// 下面兩句是通過==對比對象,當然是false了System.out.println("a_1 == b_1 ---- " + (a_1 == b_1));// falseSystem.out.println("c_1 == d_1 ---- " + (c_1 == d_1));// false// 下面兩句是通過equals對比對象,integer類裡面重寫了equals方法// 看看重寫後equals方法的代碼// public boolean equals(Object obj) {// if (obj instanceof Integer) {// return value == ((Integer)obj).intValue();// }// return false;// }// 我們可以看到出來對比對象之外,還對比本身的值,所以返回trueSystem.out.println("a_1.equals(b_1) ---- " + a_1.equals(b_1));// trueSystem.out.println("c_1.equals(d_1) ---- " + c_1.equals(d_1));// true}}



輸出:

a == b ---- true
c == d ---- false
a_1 == b_1 ---- false
c_1 == d_1 ---- false
a_1.equals(b_1) ---- true
c_1.equals(d_1) ---- true




java-基礎入門-自動裝箱與自動拆箱留給我們的坑

聯繫我們

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