#Java 装箱拆箱java
自动装箱 把基本类型用它们相应的引用类型包装起来,使其具备对象的性质。int包装成Integer、float包装成Float缓存
Integer num =10;实际上系统执行了 Integer num= Integer.valueOf(10);优化
public static Integer valueOf(int i) { //若是在范围range [-128, 127]便返回指向IntegerCache.cache缓存中已经存在的对象的引用,不然建立Integer新对象。 if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
自动拆箱 和装箱相反,将引用类型的对象简化成值类型的数据code
int n = num;实际上系统执行了 int i=num.intValue();对象
private final int value; public int intValue() { return value; }
java使用该机制是为了达到最小化数据输入和输出的目的,这是一种优化措施,提升效率。包装器缓存范围:效率
Boolean: (所有缓存)引用
Byte: (所有缓存)float
Character (<=127 缓存)数据
Integer (-128~127 缓存)static
Short (-128~127 缓存)
Long (-128~127 缓存)
Float (没有缓存)
Doulbe (没有缓存)