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] 。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。