美文网首页
Java自动装箱与拆箱

Java自动装箱与拆箱

作者: 夜阑w | 来源:发表于2019-02-18 21:23 被阅读0次

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

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

    要点:

    • 自动装箱时编译器调用valueOf将原始类型值转换成对象,同时自动拆箱时,编译器通过调用类似intValue()、doubleValue()这类的方法将对象转换成原始类型值。
    Integer iObject = Integer.valueOf(3);
    Int iPrimitive = iObject.intValue()
    
    • 自动装箱是将boolean值转换成Boolean对象,byte值转换成Byte对象,char转换成Character对象,float值转换成Float对象,int转换成Integer,long转换成Long,short转换成Short,自动拆箱则是相反的操作。
    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");
        }
    }
    

    相关文章

      网友评论

          本文标题:Java自动装箱与拆箱

          本文链接:https://www.haomeiwen.com/subject/dwizeqtx.html