Let's take a look at the output of the following question?
1 Integer a1 = New INTEGER (1, 127 ); 2 3 Integer a2 = New INTEGER (1, 127 ); 4 5 System. Out. println (a1 = A2 ); 6 7 8 Integer b1 =New INTEGER (1, 128 ); 9 10 Integer b2 = New INTEGER (1, 128 ); 11 12 System. Out. println (b1 = b2 );
Many people will say that this is too simple. Both of them must be false, because they are all different objects. When using = for comparison, it must be false.
Indeed, congratulations!
Now let's take a look at the following question.
1Integer a1 = 127;2 3Integer a2= 127;4 5System. Out. println (a1 =A2 );6 7Integer b1 = 1, 128;89Integer b2 = 128;10 11System. Out. println (b1 = b2 );
Don't be so anxious to answer the question. Think carefully. If your answer is the same as above, please read the explanation below carefully!
Because Java automatic packing is involved here, we will first introduce the concept of automatic packing.
When weCodeJava compilerDuring compilation, the integer. valueof () method is added to the class. This is equivalent
Integer I = integer. valueof (15) This is automatic packing.Reduces the impact of automatic packing on performance,Java
-After an integer between 128 and 127 is packed as an interger object, this object will be repeatedly used by another automatic packing operation on this integer, that is, multiple times for the same-128
The integer in the range of 127 is used to pack the integer, which is the object generated during the first packing operation. Therefore, the first answer is true. The second is false.
Now I believe you have a simple understanding of interger's automatic packing! So when should we use automatic packing?
Official suggestions:
So when shoshould you use autoboxing and unboxing? Use them only when there is an "impedance mismatch" between reference types and primitives,
For example, when you have to put numerical values into a collection. it is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. an integer is not a substitute for an int; autoboxing and unboxing blur the distinction
Primitive types and reference types, but they do not eliminate it.