SoFunction
Updated on 2025-03-08

Detailed explanation of Java shallow and deep replication examples

Detailed explanation of Java shallow and deep replication examples

1 The difference between shallow copy and deep copy

Shallow copy: Shallow copy just copy the original data type of this object, such as int, float, and String, and will not copy arrays and object references. Therefore shallow replication is risky.

Deep copy: Not only does it copy the original data type, it also copies the array and object references in the object, thereby achieving complete copying of the object.

2 Code Examples

package com; 
 
import ; 
 
public class Test implements Cloneable { 
 
  // Private attributes  private ArrayList<String> nameList = new ArrayList<String>(); 
 
  // Add content  public void add(String s) { 
    (s); 
  } 
 
  // Get an ArrayList object  public ArrayList<String> get() { 
    return ; 
  } 
 
  // clone method  @Override 
  public Test clone() { 
    try { 
      Test test = (Test) (); 
       = (ArrayList<String>) ();  //A 
      return test; 
    } catch (CloneNotSupportedException e) { 
      // TODO Auto-generated catch block 
      (); 
    } 
    return null; 
  } 
 
  /** 
   * @param args 
   */ 
  public static void main(String[] args) { 
    // Create a test object    Test test = new Test(); 
    // Set the content of the test object    ("aa"); 
    ("bb"); 
 
    // Print and display the nameList content in the test    ("test:" + ()); 
 
    //Clone the test object to generate the test2 object    Test test2 = (); 
    // Add "cc" content to test2 object    ("cc"); 
    // Print and display the nameList content in test2    ("test2:" + ()); 
 
    // Print and display the nameList content in the test    ("test:" + ()); 
 
  } 
} 

3 shallow copy run results

test:[aa, bb]
test2:[aa, bb, cc]
test:[aa, bb, cc]

4 Deep copy run results

test:[aa, bb]
test2:[aa, bb, cc]
test:[aa, bb]

5 Results Analysis

From the perspective of result analysis and code, deep copy only has more code at A for shallow copy.

If you have any questions, please leave a message or go to the community of this site to exchange and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!