Java Tips ---- List Copy: shallow copy and deep copy

Original Address:  https://blog.csdn.net/demonliuhui/article/details/54572908

List shallow copy

Write pictures described here

As we all know, the list is essentially an array, and an array of address form is stored. 
After the above figure the List A shallow copy to List B, as a result of the shallow copy, the copy directly from A to the B, the array pointing to the same address java in the same content, i.e. shallow copy A and B point to the same address . The consequences of that change B will also change the A, B because change is to change the contents of the address pointed to B because A is also pointing to the same address, so A change with B.

Several shallow copy

1, copy traversal cycle

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

 

2, implemented using class constructor List

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

3, using list.addAll () method

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

 

4, using System.arraycopy () method

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

 

Testing and results

printList (destList); // print unaltered A before B 
srcList.get (0) .setAge (100); // change B   
printList (destList); // after printing change B A
 // print result 
123-- > 20 is   
the ABC -> 21 is   
ABC -> 22 is   
123 -> 100   
the ABC -> 21 is   
ABC -> 22 is

List deep copy

Write pictures described here

As shown, a deep copy is copied while the A to B and B to create a new address, then the contents of the address A is transferred to the address B. ListA ListB consistent with the content, but because of the different points of address, change each other is not affected.

Deep copy method

1. Serialization Methods

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);  //调用该方法

 

Java对对象和基本的数据类型的处理是不一样的。在Java中用对象的作为入口参数的传递则缺省为”引用传递”,也就是说仅仅传递了对象的一个”引用”,这个”引用”的概念同C语言中的指针引用是一样的。当函数体内部对输入变量改变时,实质上就是在对这个对象的直接操作。 除了在函数传值的时候是”引用传递”,在任何用”=”向对象变量赋值的时候都是”引用传递”。

2.clone方法

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());
}

 

Java objects and basic data type of processing is not the same. In passing Java objects used as the entry of the default parameter is "passing by reference", that is just passing an object of "reference", the "reference" concept with the C language pointer references the same. When the functions that change the input variables, that is, substantially direct manipulation of the object. In addition to pass when the function value is "passing by reference", any of "=" assignment to the subject when the variables are "passed by reference."

Testing and results

printList (destList); // print unaltered A before B 
srcList.get (0) .setAge (100); // change B   
printList (destList); // print the changed A B
  
123 -> 20 is   
the ABC - -> 21 is   
ABC -> 22 is   
123 -> 20 is   
the ABC -> 21 is   
ABC -> 22 is  

 

In the case of a shallow copy, after the destruction of the source data is modified, the same reference point corresponding to the set of data elements of the target in the same change also occurs. Thus, in a case where the demand requirements must be deep copy, and if using the method mentioned above, make sure the List T class object is destroyed and can not easily be modified outside.

Guess you like

Origin www.cnblogs.com/charles8866/p/10973128.html