Automatic packing, automatic unpacking

Before jdk1.5, you need to store basic data types in wrapper classes like this:
Integer iObj = new Integer(5);
int i = iObj.intValue();
After jdk1.5, java introduced new features, automatic boxing and automatic unboxing.
So it can be written like this:
Integer i = 5 ;
Java has a total of eight basic data types, each of which has a corresponding wrapper class.
basic data type
Packaging class
byte
Byte
short
Short
int
Integer
long
Long
char
Character
float
Float
double
Double
boolean
Boolean


Autoboxing:
Integer i = 10;
In fact, the compiler does some extra operations for us. The decompiled code should be as follows:
Integer i = Integer.valueOf(10);

Automatic unboxing:
int x = i;
After decompiling:
int x = i.intValue();

Integer a = 100;
Integer b = 100;
Integer c = 200;
Integer d = 200;
syso(a == b);
syso(c == d);


The output is
true
false
When Integer creates an Integer object through the valueOf method, when the value range is between [-128, 127], it will point to the application of an existing object, otherwise a new Integer object will be created.

If the type of the above question is changed to double type, both results are false
Note that the implementation of the valueOf method of the Integer, Short, Byte, Character, and Long classes is similar.
The implementation of the valueOf method of Double and Float is similar.


When both operands of the "==" operator are references of the wrapper type, the comparison is made to see if they point to the same object, and if one of the operands is an expression (that is, contains an arithmetic operation), the comparison is made is a numeric value (i.e. triggers the process of automatic unboxing). Also, for wrapper types, the equals method does not perform type conversions.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326945721&siteId=291194637