I have some understanding of automatic boxing and unboxing, and I hope it will be helpful to everyone.
The method of automatic boxing and automatic unboxing:
Automatic boxing method: java source code is as follows:
private static class IntegerCache{
static final Integer cache[];
static{
对-128到127对象的创建
}
}
public static Integer valueOf(int i){
if(i <= IntegerCache.high && i >= IntegerCache.low)
return IntegerCache.chache[i - IntegerCache.low];
return new Integer(i);
}
Integer class has a static inner classes IntegerCache the (class-level inner classes), which for some commonly used int numbers, to be exact is a number between -128 and 127 created Integer object and placed in a
static
buffer array Medium (Integer cache []).
Integer i = 100; The actual code for completion is: Integer i = Integer.valueOf (100); Since 100 is in the cached value range (-128-127), no new Integer object is created, but a reference The objects in the Integer cache [] array within IntegerCache (static data, shared by objects of this type).
Integer j = 200; The actual code for completion is: Integer i = Integer.valueOf (100); but it does call new Integer (200); the constructor creates the object.
Examples:
public static void main(String[] args) {
Integer a=100;
Integer b=100;
Integer c=200;
Integer d=200;
System.out.println(a==b); //1
System.out.println(a==100); //2
System.out.println(c==d); //3
System.out.println(c==200); //4
}
The result is true true false true
Unboxing calls the
java source code as follows:
private final int value;
public Integer(int value){
this.value = value;
}
public int intValue(){
return value;
}