Object wrappers
Each type has a corresponding base class called wrapper warpper .
/* extends Number */
// Interger <-> int
// Long <-> long
// Float <-> float
// double <-> double
// Short <-> short
// Byte <-> byte
/* not extends Number */
// Character <-> character
// Void <-> void
// Boolean <-> boolean
Packaging the object is immutable : once the configuration of the wrapper, the packaging is not allowed to change the value therein.
Object wrapper are final
: the definition of the object can not be a subclass of the wrapper.
Autoboxing (auto boxing)
Declare an Integer
array list object and add a value of 3 Integer
objects.
// 由于值包装在对象中,ArrayList<Integer>的效率远低于int[]数组。
ArrayList<Integer> list = new ArrayList<>();
// 等价于list.add(Integer.valueOf(3));
list.add(3);
On the contrary, the Integer
object is assigned to int
the time variable, it will automatically unpack .
// 编译器将以下语句翻译成int n = list.get(i).inValue();
int n = list.get(i);
It can be automatically boxing and unboxing in arithmetic expressions.
Integer n = 3;
// 编译器会自动地插入一条对象拆箱指令,在自增计算执行后,执行装箱指令。
n++;
Compare wrapper
Object wrapper equality with different basic types:
Integer a = 1000;
Integer b = 1000;
// ==检测a和b是否指向同一个存储区域,结果是false
System.out.println(a == b);
// equals方法比较a和b包装的值,结果是true
System.out.println(a.equals(b));
There are automatic packing specifications of ranges of values basic types: boolean
, byte
, char
≤ 127 , between -128 to 127 between short
and int
are packed in a fixed object, which points to the same memory area.
Integer a = 100;
Integer b = 100;
// 此时a和b指向同一个存储区域,结果是true
System.out.println(a == b);
Abnormal null reference
Packaging Cite null, autoboxing may throw NullPointerException
an exception:
Integer n = null;
// 由于n引用null,执行2 * n时会将n自动拆箱取值,抛出NullPointerException异常。
System.out.println(2 * n);
auto update
Further mixed using conditional expressions Integer
and Double
when the Integer
value unpacking promoted double
, then packing as Double
:
Integer n = 1;
Double x = 2.0;
// n升级为Double,结果是1.0
System.out.println(true ? n : x);
Note : boxing and unboxing is a compiler recognized, instead of the virtual machine. The compiler generates bytecode classes and then, inserts the necessary method call.