-------------------- Android training, Java training, and hope to communicate with you! ----------------------
One of the new features introduced by Java is automatic packing and unpacking. First, we need to know why there are automatic unpacking and packing, Because Java has eight basic data types, we also provide objects that correspond to eight basic data types one by one. Why are these objects provided? That's because sometimes we need to convert the basic data type to an object, for example, when you use a map object to operate the remove () method, the parameter to be passed in is the object rather than the basic data type, if you need to convert the basic data type to an object every time, you need to use
Integer I = new INTEGER (1); this is troublesome. Therefore, after Java, a simple method is provided, that is, a virtual machine automatically converts the data for you, you only need to write integer I = 1; in this process, the Java Virtual Machine automatically loads 1 into an object, so it is called automatic packing. Similarly, you do not need to use int I = (integer object) to convert an object to a basic data type ). intvalue () is written in this way, as long as int I = (integer object) is enough, this is the automatic unpacking. However, you need to pay attention to the use of automatic unpacking and packing. For example, compare the results of the following two sub-statements:
1
Integer i1 = 200;Integer i2 = 200;if(i1 == i2) System.out.println(i1 == i2);else System.out.println(i1 == i2);
2
Integer i1 = 20;Integer i2 = 20;If(i1 == i2) System.out.println(i1 == i2);else System.out.println(i1 == i2);
According to the automatic packing and unpacking mechanism, we will think that the results are equal, but the results are indeed different. In fact, = is used to compare whether the values of two basic data types are equal, it is also used to determine whether two object reference names refer to the same object. After the values between-128 and 127 are automatically packed into integer objects, memory is reused. Therefore, when I1 and I2 are in the same byte, they refer to the same object. However, if they exceed one byte, the boxed integer object is not reused. All I1 and I2 are not equal when compared with =.
-------------------- Android training, Java training, and hope to communicate with you! ----------------------
For details, see edu.csdn.net/heima.