自动装箱拆箱原理及使用误区

本文详细介绍了Java中自动装箱与拆箱的过程及原理,包括Integer对象的复用机制,以及何时应该使用自动装箱和拆箱。并探讨了在不同场景下使用自动装箱和拆箱的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自动装箱与拆箱
1.实际上在编译器编译过程中使用Integer.valueOf(xxx)转换成Integer对象
拆箱则是调用integer对象的intValue方法;(可以自行查看.class文件)

2.Integer.valueOf(xxx)
默认情况是-128~127返回原始值
超过范围则返回Integer对象,因此
Integer i = 200;
Integer j = 200;
i == j是false
查看下面的源码
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);
}


  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) {
int i = parseInt(integerCacheHighPropValue);
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - (-low));
}
high = h;

cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}


从源码中可以看出high的值是可以在property中配置,因此对于两个Integer对象的比较最好使用equals方法。
3.那么什么时候使用自动装箱(autoboxing)和自动拆卸(unboxing)呢?
在引用类型(也即是包装类)与原生数据类型之间存在 “阻抗失谐”时,比如你想将一个数值 放入到 collection中。包括Integer的初始值为null,int的默认值是0。当0有实际含义时用Integer是有必要的。
在科学计算或者其他性能要求高的数字计算中,是不适合使用自动装箱(autoboxing)和自动拆卸(unboxing)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值