The use of Java automatic Unpacking is very extensive. But there are some "traps" in it. Nonsense not to say, to see 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));
Printing results:
True
True
True
False
True
If all of the above operations are automatically disassembled, the printed result should be true. Here First explain the = = symbol does not occur automatically unpacking, so there are the above problems. But look closely, some people will say, that is not Ming C==d? In order to solve the mystery, we have to understand the boxing process. Let's take a look at the disassembly results for the above code:
From the above code snippet can be found that the original is called Integer.valueof This class method. Let's take a look at this class method:
/** * Returns a {@code integer} instance for the specified integer value. * <p> * If It isn't necessary to get a new {@code Integer} instance, it's * recommended to use the 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 >= | | i < -128? New integer (i): Small_values[i + +]; }
/** * A cache of instances used by {@link integer#valueof (int)} and auto-boxing * * private static final int eger[] small_values = new integer[256];
Seeing the above code, I believe it is clear why the above results have occurred. Because [-128,127] was cached.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Automatic Unpacking traps