天天看点

Java的自动装箱与拆箱

1.什么是自动装箱与自动拆箱?

       Demo:

Integer int1 = 100;
Integer int2 = 100;
Integer int3 = 200;
Integer int4 = 200;
System.out.println(int1==int2);//true
System.out.println(int3==int4);//false           
//自动装箱
Integer int1 = 100;
//自动拆箱
int int2 = int1;           

       简单点说,装箱就是自动将基本数据类型转换为包装类型;拆箱就是自动将包装类型转换为基本数据类型。八种基本数据类型都可进行自动装箱:

Java的自动装箱与拆箱
public final class Integer extends Number implements Comparable<Integer> {
    private final int value;
    public Integer(int value) {
        this.value = value;
    }
    public Integer(String s) throws NumberFormatException {
        this.value = parseInt(s, 10);
    }
}           
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];

        //上述代码可以简化如下
        //if (i >= -128 && i <= 127)
        //     return IntegerCache.cache[i + 128];

        return new Integer(i);
}