Java automatic unpacking traps and java traps
Java automatic unpacking is widely used. But there are some "traps ". Let's look at a piece of code:
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));}
Print result:
True
True
True
False
True
If all the preceding operations are automatically split, the printed result should be true. The = symbol does not automatically split the box, so the above problem occurs. But after a closer look, someone will say, isn't it clearly c = d? To solve the mystery, we must understand the packing process. Let's take a look at the disassembly result of the above Code:
From the code snippet above, we can see that the class method Integer. valueOf was called. Let's take a look at this class method:
/** * 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];
Seeing the above code, I believe it is clear why the above results have occurred. Because [-128,127] is cached.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.