转载:https://www.cnblogs.com/dolphin0520/p/3780005.html
https://www.cnblogs.com/wang-yaz/p/8516151.html
1、基本类型通过装箱(valueOf())可以变成包装类型。
2、包装类型通过拆箱(xxxValue())可以 变成基本类型。
3、装箱详解
类型 | 相同对象范围 | 不同对象范围 |
---|---|---|
Integer | (-128,128) | i>=128 || i<-128 |
Short | (-128,128) | s>=128 || s<-128 |
Character | c<128 | c>=128 |
Long | (-128,128) | l>=128 || l<-128 |
此图的意思是,以Integer为例,
int i = 1; int a = 1; 装箱之后,i==a;如果 int i = 200; int a = 200; 装箱之后,i!=a;原因如下:
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);
}
Double类型,不论数值范围,装箱后都是new了一个新对象。
Float类型,不论数值范围,装箱后都是new了一个新对象。
4、==和equals
==,当运算符两边都是包装器类型时,比较的是是否指向同一个对象,当有一边是基本类型,则自动触发拆箱过程,比较数值。
equals,比较内容的,如果一边是包装器类型,则不会进行类型转换。