java 自動拆箱的陷阱,java陷阱

來源:互聯網
上載者:User

java 自動拆箱的陷阱,java陷阱

  java  自動拆箱運用非常廣泛。但是這裡面有一些“陷阱”。廢話不多說,來看一段代碼:

 

public static void main(String[] args) {Integer a=1;Integer b=2;Integer c=3;Integer d=3;System.out.println(c==(a+b));System.out.println(c==d);System.out.println(c.equals(d));Integer f=200;Integer e=200;System.out.println(e==f);System.out.println(e.equals(f));}

列印結果:

true

true

true

false

true

如果說以上的運算都進行自動拆箱那列印的結果應該都是true。在這裡先說明一下== 符號並不會發生自動拆箱,所以也就出現了以上的問題。但是仔細觀察一下,就有人會說,那不是明明c==d嗎?為瞭解開謎團,我們必須要瞭解這個裝箱過程。我們來看一下對以上代碼的反組譯碼結果:



從以上的程式碼片段可以發現,原來是調用了Integer.valueOf這個類方法。我們來看一下這個類方法:

  /**     * Returns a {@code Integer} instance for the specified integer value.     * <p>     * If it is not necessary to get a new {@code Integer} instance, it is     * recommended to use this method instead of the constructor, since it     * maintains a cache of instances which may result in better performance.     *     * @param i     *            the integer value to store in the instance.     * @return a {@code Integer} instance containing {@code i}.     * @since 1.5     */    public static Integer valueOf(int i) {        return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];    }

    /**     * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing     */    private static final Integer[] SMALL_VALUES = new Integer[256];

看到以上的代碼,我相信清楚了為什麼會發生以上的結果了。因為緩衝了[-128,127] 。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

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