当前位置:首页 > 分类 > JAVA基础 > JDK源码-Integer装箱与拆箱
JDK源码-Integer装箱与拆箱
作者:admin
2020-12-25 09:46
热度:83
1,自动装箱
如
Integer a = 1;
这样的代码会自动装箱,也就是会调用Integer类的static valueOf(int i)方法;
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
如果数字i在low和high之间,将从缓存中取出已经实例化好的实例;否则实例化integer对象。数字值则用integer类的成员变量value保存。
下面打个断点验证下
可见对象a的value为1。表示确实已经把等号右边的1转换成了integer类实例。
下面看缓存代码
static {
// high value may be configured by property
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
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);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
默认范围为-128到127,也就是在这个范围内自动装箱返回的对象都是缓存中获取的。注意像Integer a = new Integer(1)的代码没有装箱过程。
同时high是可配置的,可通过添加-Djava.lang.Integer.IntegerCache.high=xxx或-XX:AutoBoxCacheMax=xxx启动配置项来配置high的值,但由于会把范围内的数字都实例化保存在缓存中,所以配置时需要注意。
如,在main方法run as->run configurations->arguments->vm arg中添加
-XX:AutoBoxCacheMax=130
测试代码
Integer aa = 129;
Integer bb = 129;
System.out.println(aa==bb);//true
Integer cc = 131;
Integer dd = 131;
System.out.println(cc==dd);//false
2,自动拆箱
如
int a = new Integer(1);
这样的代码会自动拆箱,也就是调用integer类的intValue方法。从包装类转换成基本类型。
public int intValue() {
return value;
}
但实际应用中不会写这样的代码,看下面一段代码
Integer a = 1;
int b = a;
System.out.println(a==b);
第一行自动装箱
第二行自动拆箱
第三行,当a与基本数据类型b比较时,会对a自动拆箱,返回true。