您的位置:首页 > 其它

初学者对自动装箱和自动拆箱的认识(IntegerCache的缓存数组)

2017-12-03 22:36 337 查看
自己对自动装箱和拆箱的一些认识,希望对大家有所帮助,不足和错误之处还望之处。

自动装箱,自动拆箱调用的方法:
自动装箱调用的方法: java源码如下:
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类中有个IntegerCache的静态内部类(类级内部类),里面对一些常用的int数字,准确的说是-128到127之间的数字进行Integer对象的创建,并放在一个静态缓存数组中(Integer cache[])。
Integer i = 100; 补全的实际代码为: Integer i = Integer.valueOf(100);由于100在缓存的数值范围内(-128——127)所以,并没有创建新的Integer对象,而是引用IntegerCache内部的Integer cache []数组中的对象(静态数据,该类对象所共有)。
Integer j = 200; 补全的实际代码为:Integer i = Integer.valueOf(100);但是其调用的确实new Integer(200);构造器进行对象创建。
举例:
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
}

结果是,true true false true
拆箱调用的是
java源码如下:
private final int value;
public Integer(int value){
this.value = value;
}
public int  intValue(){
return value;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: