zoukankan      html  css  js  c++  java
  • Java基础 深拷贝浅拷贝

    Java基础 深拷贝浅拷贝

    • 非基本数据类型 需要new新空间
    class Student implements Cloneable{
        private int id;
        private String name;
        private Vector course;
    
        public Student(){
            try{
                Thread.sleep(1000);
                System.out.println("Student Constructor called.");
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    
        public String getName() {return name;}
        public void setName(String name) {this.name = name;}
    
        public int getId() {return id;}
        public void setId(int id) {this.id = id;}
    
        public Vector getCourse() {return course;}
        public void setCourse(Vector course) {this.course = course;}
    
        //浅拷贝
        public Student newInstance(){
            try{
                return (Student)this.clone();
            }catch (CloneNotSupportedException e){
                e.printStackTrace();
            }
            return null;
        }
    
        //深拷贝
        public Student deepClone(){
            try{
                Student cloning = (Student) super.clone();
                cloning.course = new Vector();
                return cloning;
    
            }catch (CloneNotSupportedException e){
                e.printStackTrace();
            }
            return null;
        }
    
    }
    
    
    public Object clone(){      //覆写clone(),深拷贝  
        try{  
            Student cloning = (Student) super.clone(); 
            // 这里不能使用Student cloning = (Student) this.clone()的原因:
            正在覆写本类的clone()方法,如果再调用本类的函数,即:this.clone(),就相当于无限递归无限死循环了,最终会崩溃的。所以这里:super.clone()。
    
            cloning.courses = new Vector();     //关键点:非基本数据类型的空间需要自己新开辟一块儿  
            return cloning;  
        }catch(CloneNotSupportedException e){  
            e.printStackTrace();  
        }  
        return null;  
    }  
    
    

    参考资料

    谨慎覆盖clone
    Java中的clone() 深拷贝 浅拷贝

  • 相关阅读:
    Python环境搭建
    appium的android端的环境搭建(Window)
    Unittest中常用的十四种断言方法
    Leetcode-141(判断链表是否存在环)
    Leetcode-88(归并两个有序数组)
    Leetcode-680(回文字符串)
    Leetcode-345(反转字符串中的元音字符)
    Leetcode-633 (两数平方和)
    Leetcode-167(有序数组的 Two Sum)
    判断是否为小数
  • 原文地址:https://www.cnblogs.com/ironbrady/p/6671860.html
Copyright © 2011-2022 走看看