Shallow copy and deep copy problem java

Topic details:

Object Copy in Java refers to copying all properties (member variables) of an object to another object with the same class type. For example: For example, object A and object B both belong to class S and have attributes a and b. Then copying object A and assigning it to object B is: Ba=Aa; Bb=Ab;

Shallow Copy : ① For a member variable whose data type is a basic data type, the shallow copy will directly transfer the value, that is, copy the attribute value to a new object. Because it is two different pieces of data, modifying the value of the member variable of one object will not affect the data copied by the other object.

②For a member variable whose data type is a reference data type, for example, a member variable is an array, an object of a certain class, etc., then the shallow copy will be passed by reference, that is, only the reference value (memory address) of the member variable. Make a copy to the new object. Because in fact the member variables of both objects point to the same instance. In this case, modifying the member variable in one object will affect the value of the member variable in the other object. To solve this problem, introduce deep copy :

Deep copy  For reference type member variables, such as arrays or class objects, deep copy will create a new object space in the target object, and then copy the contents of the corresponding member variable entity object of the original object, so they point to different memory spaces. Changing one of them will not affect the other.

There is a method in Java called protected Object clone() throws CloneNotSupportedException, which is a shallow copy. To implement a deep copy of a class, it needs to implement the Cloneable interface, and then rewrite the clone method

Override the clone method definition:

class Car implements Cloneable{  //定义一个Car类 实现接口Cloneable
       //成员变量定义
   public Object clone(){  //重写clone方法
       Car c = null;
        try {
                c = (Car)super.clone(); //调用父类Object实现浅拷贝
               } catch (CloneNotSupportedException e) {
                        e.printStackTrace();
               }
            //编写代码实现深拷贝

      }
    //编写代码实现其他成员方法
}

Car class contains

1. Properties:

private String name;
private CarDriver driver;
private int[] scores;

2. No-argument constructor

public Car() {
}

3. Member method:

@Override
public String toString() {
    return "Car [name=" + name + ", driver=" + driver + ", scores=" + Arrays.toString(scores) + "]";
}

4. Other get and set member methods: public String getName(), public CarDriver getDriver(), public int[] getScores() and

public void setName(String name),public void setDriver(CarDriver dr),public void setScores(int[] s)

and  clonemethod to implement deep copy

CarDriverFor the defined class, as follows:

class CarDriver {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public CarDriver() {}
    public String toString() {
        return "CarDriver [name=" + name+"]";
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int i=sc.nextInt();
        switch(i) {
        case 1:     //深拷贝
            CarDriver cd=new CarDriver();
            Car c1=new Car();
            c1.setDriver(cd);
            cd.setName("d1");
            c1.setName("car1");
            int[] s=new int[2];
            c1.setScores(s);
            Car d1=(Car)c1.clone();
            System.out.println("c1:"+(c1==d1)+" driver:"+(c1.getDriver()==d1.getDriver())+" scores:"+(c1.getScores()==d1.getScores()));
            System.out.println(c1.toString()+" "+d1.getName()+" "+d1.getDriver().getName());    
            break;
        case 2: //        
            Car c2=new Car();
            Car d2=(Car)c2.clone();
            System.out.println("c2:"+(c2==d2)+" driver:"+c2.getDriver()+" "+(c2.getDriver()==d2.getDriver())+" scores:"+c2.getScores()+" "+(c2.getScores()==d2.getScores()));
            break;
        case 3:
            CarDriver cd1=new CarDriver();
            Car c3=new Car();
            c3.setDriver(cd1);
            Car d3=(Car)c3.clone();
            System.out.println("c3:"+(c3==d3)+" driver:"+c3.getDriver()+" "+(c3.getDriver()==d3.getDriver())+" scores:"+c3.getScores()+" "+(c3.getScores()==d3.getScores()));
            break;
        case 4:
            //CarDriver cd3=new CarDriver();
            Car c4=new Car();
            //c4.setDriver(cd3);
            int[] s1=new int[2];
            c4.setScores(s1);
            Car d4=(Car)c4.clone();
            System.out.println("c4:"+(c4==d4)+" driver:"+c4.getDriver()+" "+(c4.getDriver()==d4.getDriver())+" scores:"+" "+(c4.getScores()==d4.getScores()));
            break;

        } 
    }
}

//Now you just need to write the complete code of the Car class below

Answer code:

class Car implements Cloneable{
    private String name;
    private CarDriver driver;
    private int[] scores;
    public Car() {
}
    public String getName() {
		return name;
	}
	public CarDriver getDriver() {
		return driver;
	}
	public int[] getScores() {
		return scores;
	}
	public void setName(String name){
	       this.name=name;
	   }
	public void setDriver(CarDriver dr){
	       this.driver=dr;
	   }
	public void setScores(int[] s){
	       this.scores=s;
	   }
    @Override
    public String toString() {
    	return "Car [name=" + name + ", driver=" + driver + ", scores=" + Arrays.toString(scores) + "]";
    }
    public Object clone(){
       Car c = null;
       try {
    	   c = (Car)super.clone();
       } catch (CloneNotSupportedException e) {
    	   e.printStackTrace();
       }
	  if(driver!=null) {
        c.driver=new CarDriver();
       if(driver.getName()!=null)
        c.driver.setName(new String(this.driver.getName()));
	  }
      if(name!=null)
        c.name=new String(this.name);  
      if(scores!=null) {
        c.scores=new int[this.scores.length];
       for(int i=0;i<this.scores.length;i++){
           c.scores[i]=this.scores[i];
         }
       }    
       return c;
   } 
}

Guess you like

Origin blog.csdn.net/qq_54587141/article/details/120744203