1.需要自动拆箱装箱的类型
2. 基本类型及其包装类型
.什么是自动拆箱装箱
装箱,就是将基本数据类型转换成包装器类型。
拆箱,就是自动将包装类型转换成基本数据类型
//自动装箱 Integer total = 99; //自动拆箱 int totalprim = total;
看个栗子
public class StringTest { public static void main(String[] args) { //自动装箱 Integer total = 99; //自定拆箱 int totalprim = total; } }
编译Java源码
javac StringTest.java javap -c StringTest.class
javap 查看汇编命令结果
D:\ideaworkspace\test\src\testtool>javap -c StringTest.class Compiled from "StringTest.java" public class testtool.StringTest { public testtool.StringTest(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: bipush 99 2: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 5: astore_1 6: aload_1 7: invokevirtual #3 // Method java/lang/Integer.intValue:()I 10: istore_2 11: return }
自动装箱
执行 Integer total =99;
执行代码时系统为我们执行了 Integer total = Integer.valueOf(99);
这个就是自动装箱。
/** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */ public static Integer valueOf(int i) { if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
自动拆箱
执行 int totalprism = total 时 系统自动执行了
int totalprim = total.intValue();
/** * Returns the value of this {@code Integer} as an * {@code int}. */ public int intValue() { return value; }