Java List Copy: Shallow Copy and Deep Copy (General)

directory (?)[+]

List shallow copy

write picture description here

As we all know, lists are essentially arrays, and arrays are stored in the form of addresses. 
As shown in the figure above, list A is shallowly copied to list B. Since it is a shallow copy, the content of A is directly copied to B. The array of the same content in java points to the same address, that is, A and B point to the same address after the shallow copy. . The consequence is that changing B will also change A, because changing B is changing the content of the address pointed to by B. Since A also points to the same address, A and B are changed together.

several shallow copies

1. Traverse loop copy

List<Person> destList=new ArrayList<Person>(srcList.size());  
for(Person p : srcList){  
    destList.add(p);  
}  
  • 1
  • 2
  • 3
  • 4

2. Use List to implement the class constructor

List<Person> destList=new ArrayList<Person>(srcList);  
  • 1

3. Use the list.addAll() method

List<Person> destList=new ArrayList<Person>();  
destList.addAll(srcList);  
  • 1
  • 2

4. Use the System.arraycopy() method

Person[] srcPersons=srcList.toArray(new Person[0]);  
Person[] destPersons=new Person[srcPersons.length];  
System.arraycopy(srcPersons, 0, destPersons, 0, srcPersons.length);  
  • 1
  • 2
  • 3

Tests and Results

printList(destList); //打印未改变B之前的A 
srcList.get(0).setAge(100);//改变B  
printList(destList); //打印改变B后的A

//打印结果
123-->20  
ABC-->21  
abc-->22  
123-->100  
ABC-->21  
abc-->22  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

List deep copy

write picture description here

As shown in the figure, a deep copy is to create a new address for B while copying A to B, and then transfer the content of address A to address B. The contents of ListA and ListB are the same, but because the addresses pointed to are different, the changes do not affect each other.

deep copy method

1. Use the serialization method

public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {  
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();  
    ObjectOutputStream out = new ObjectOutputStream(byteOut);  
    out.writeObject(src);  

    ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());  
    ObjectInputStream in = new ObjectInputStream(byteIn);  
    @SuppressWarnings("unchecked")  
    List<T> dest = (List<T>) in.readObject();  
    return dest;  
}  

List<Person> destList=deepCopy(srcList);  //调用该方法
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2.clone method

public class A implements Cloneable {   
    public String name[];   

    public A(){   
        name=new String[2];   
    }   

    public Object clone() {   
        A o = null;   
        try {   
            o = (A) super.clone();   
        } catch (CloneNotSupportedException e) {   
            e.printStackTrace();   
        }   
        return o;   
    }   
}  
for(int i=0;i<n;i+=){
copy.add((A)src.get(i).clone());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

Java handles objects and basic data types differently. Passing an object as an entry parameter in Java defaults to "pass by reference", which means that only a "reference" of the object is passed. The concept of this "reference" is the same as the pointer reference in the C language. When the input variable is changed inside the function body, it is essentially a direct operation on the object. Except when the function is passed by value, it is "pass by reference", and any assignment to an object variable with "=" is "pass by reference".

Tests and Results

printList(destList); //打印未改变B之前的A 
srcList.get(0).setAge(100);//改变B  
printList(destList); //打印改变B后的A

123-->20  
ABC-->21  
abc-->22  
123-->20  
ABC-->21  
abc-->22  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

In the case of shallow copying, after the source data is modified and destroyed, the corresponding elements in the target collection that use the same reference to point to the data also undergo the same changes. Therefore, if the requirement requires deep copying, if you use the method mentioned above, please ensure that the T class object in the List is not easily modified and destroyed by the outside.

Reference: 
http://blog.csdn.net/lian_1988/article/details/45970927  
http://blog.sina.com.cn/s/blog_605f78830102uy6x.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324852060&siteId=291194637