Java automatic unpacking and packing
Java 1.5 introduces the automatic packing and unpacking Mechanism
Automatic packing: (check the code)
// Automatic packing: Wrap the basic types with their corresponding reference types so that they have the object property Integer integer_a = 8;
Automatic unpacking: (check the code)
// Automatic unpacking: simplifies the reference type objects such as Integer into basic data.
int a = new Integer(8);
Note: automatic packing and unpacking are completed by the compiler. during compilation, the compiler determines whether to perform packing and unpacking Based on the syntax.
Java uses the automatic packing and unpacking mechanism, which saves the memory overhead of common values and the overhead of object creation and improves the efficiency.
(1) various comparisons can be made between Integer and int. The Integer object will be automatically split and compared with the int value (see the code)
Integer integer_a = 8;int a = 8;System.out.println(integer_a == a);// trueSystem.out.println(integer_a > a);// falseSystem.out.println(integer_a < a); // falseInteger integer_b = 200;int b = 200;System.out.println(integer_b == b);// trueSystem.out.println(integer_b > b); // falseSystem.out.println(integer_b < b); // false
(2) Two Integer objects can also be used>, <等符号比较大小,两个integer对象都拆箱后,再比较大小(看代码)< p>
Integer integer_c = 8; Integer integer_d = 200; System. out. println (integer_c> integer_d); // false System. out. println (integer_c
(3) we recommend that you do not use = to compare two Integer objects. Because:-128 ~ The range of 127 (generally in this range) is used to fetch objects in the cache from the automatic packing pool, so they are equal. Two different objects outside the range are referenced and compared. (View code)
Integer integer_a_one = -128;Integer integer_b_one = -128;System.out.println(integer_a_one == integer_b_one);// trueInteger integer_a_two = 127;Integer integer_b_two = 127;System.out.println(integer_a_two == integer_b_two);// true Integer integer_c_one = -129;Integer integer_d_one = -129;System.out.println(integer_c_one == integer_d_one);// falseInteger integer_c_two = 128;Integer integer_d_two = 128;System.out.println(integer_c_two == integer_d_two);// false
Summary: The automatic packing pool corresponding to the basic data type has a certain size. You can check the source code to understand it.
Int, Byte, Short, and Long correspond to-128 ~ 127
Character corresponds to 0 ~ 127
Float and Double do not have an automatic packing pool (see the code)
Float fa=3f;Float fb=3f;System.out.println(fa==fb);//falseDouble da=3d;Double db=3d;System.out.println(da==db);//false