Java自动装箱与拆箱

2019-02-18  本文已影响0人  夜阑w

自动装箱就是Java自动将原始类型值转换成对应的对象,比如将int的变量转换成Integer对象,这个过程叫做装箱,反之将Integer对象转换成int类型值,这个过程叫做拆箱。因为这里的装箱和拆箱是自动进行的非人为转换,所以就称作为自动装箱和拆箱。

原始类型byte、short、char、int、long、float、double和boolean对应的封装类为Byte、Short、Character、Integer、Long、Float、Double、Boolean。

要点:

Integer iObject = Integer.valueOf(3);
Int iPrimitive = iObject.intValue()
public class Test {
    public static Integer show(Integer number){
        System.out.println(number);
        return number;
    }
    public static void main(String[] args) {
        show(3); //自动装箱
        int result = show(3); //拆箱
        System.out.println(result);
    }
}

注:当重载遇上自动装箱时,不会发生自动装箱操作。例:

public class Test {
    public static void main(String[] args) {
        show(3); 
        Integer number = 3;
        show(number);
        /*输出结果:
        int
        Integer*/
    }
    public static void show(Integer number){
        System.out.println("Integer");
    }

    public static void show(int number) {
        System.out.println("int");
    }
}
上一篇 下一篇

猜你喜欢

热点阅读