# 什么是自动装箱与拆箱
# 自动装箱
自动将基本数据类型转换为包装器类型. 在编译期,jvm执行了 Integer.valueOf()方法
# 自动拆箱
自动将包装器类型转换为基本数据类型. 在编译器,jvm执行了 Integer.intValue()方法
# 基本数据类型与包装器类型的对应关系
排序 | 基本数据类型 | 包装器类型 | 长度 |
---|---|---|---|
1 | byte | Byte | 1 |
2 | short | Short | 2 |
3 | char | Character | 2 |
4 | int | Integer | 4 |
5 | float | Float | 4 |
6 | long | Long | 8 |
7 | double | Double | 8 |
8 | boolean | Boolean | 未定 |
# int型自动装箱方法
public static Integer valueOf(int targetValue) {
// 整型常量缓存,默认区间在 [-128,127]
if (targetValue >= IntegerCache.low && targetValue <= IntegerCache.high)
return IntegerCache.cache[targetValue + (-IntegerCache.low)];
return new Integer(targetValue);
}
# int型自动拆箱方法
public int intValue() {
return value;
}
# 自动装箱与自动拆箱的触发规则
# 自动拆箱的规则
当一个基础数据类型与封装类型 进行 ==、四则运算 时,会将 封装类进行拆箱,对基础数据类型进行运算
# 包装类型的比较规则
- 当 两个包装类型 进行 **==**操作时,比较的是 对象本身是否相同
- new Integer() 与自动装箱拆箱的区别: new Integer不会触发常量池,因此 当两个[-128,127] 的new出来的包装类型,进行 == 操作时,返回false
# 基本数据类型与包装类型的使用标准
- 所有POJO必须使用包装数据类型
- RPC方法的返回值和参数,必须使用包装数据类型
- 所有的局部变量,使用基本数据类型