基本类型的自动装箱与自动拆箱
以Integer
为例
// 自动装箱
Integer integer = 1;
// 自动拆箱
int i = integer;
上方代码实际相当于下方代码
Integer integer = Integer.valueOf(1);
int i = integer.intValue();
自动装箱使用valueOf
方法,自动拆箱使用intValue
方法
包装类的享元模式
Byte
Short
Integer
Long
Character
Boolean
六个包装类会使用享元模式,在调用valueOf
方法时使用缓存。
Byte
Short
Integer
Long
在数字范围$[-128, 127]$使用缓存
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Charater
在数字范围$[0, 127]$使用缓存
public static Character valueOf(char c) {
if (c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
}
Boolean
全部使用缓存
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
Float
和Double
没有使用缓存
包装类之间的比较
数值相等的包装类对象在使用缓存的范围内使用==
比较,结果为true
,在缓存范围外则结果为false
如果不确定数字范围是否必然在缓存范围内,则对比时避免使用==
,应使用equals
方法进行对比
PREVIOUSDocker时区调整