# Java Auto Boxing, unpacking
jdk 1.5
starting with the version, this feature is introduced.
First, automatic packing
The base data type is automatically encapsulated as the corresponding wrapper class.
code example,
Integer i = 100;
100
is a basic type int
and will be boxed automatically, as follows:
Integer i = Integer.valueOf(100);
Equivalent
Integer i = new Integer(100);
Second, automatic unpacking
Automatically converts the encapsulated class to the corresponding base data type.
code example,
Integer i = new Integer(100);int j = i;
i
Belongs Integer
to the package class and will be automatically disassembled as follows:
Integer i = new Integer(100);int j = i.intValue();
Iii. issues
Problem code (which can cause NPE
problems),
Map<String, Boolean> map = new HashMap<String, Boolean>();Boolean b = (map != null ? map.get("test") : false);
Cause: Three mesh operator the second to third operand type is different (one for the object and one for the base data type), and the object is automatically unboxing to the base data type.
Unpacking process,
Map<String, Boolean> map = new HashMap<String, Boolean>();Boolean b = Boolean.valueOf(map != null ? map.get("test").booleanValue() : false);
Problem solving,
Map<String, Boolean> map = new HashMap<String, Boolean>();Boolean b = (map != null ? map.get("test") : Boolean.FALSE);
Related Code,
Integer int1 = 100;Integer int2 = 100;Integer int3 = 300;Integer int4 = 300; // trueSystem.out.println(int1 == int2);// falseSystem.out.println(int3 == int4);
Cause the problem: boxing is called Integer.valueOf()
. The source code is as follows
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i);}
IntegerCache
The source code is as follows
private Static class Integercache {static final int low =-128; static final int high; Static final Integer cache[]; static {//high value is configured by property int h = 127; String Integercachehighpropvalue = Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high"); if (integercachehighpropvalue! = null) {int i = parseint (Integercachehighpropvalue); i = Math.max (i, 127); Maximum array size is integer.max_value h = math.min (i, Integer.max_value-(-low)-1); } high = h; cache = new Integer[(high-low) + 1]; int j = Low; for (int k = 0; k < cache.length; k++) cache[k] = new Integer (j + +); Private Integercache () {}}
No special settings are made and the IntegerCache.high
values are 127
. Therefore, Integer.valueOf()
when you create an object through a method, Integer
if the value is in [-128,127]
between, IntegerCache.cache
a reference to the object is returned, otherwise a new object is created Integer
.
Java Automatic Boxing, unpacking