Java--List之深拷貝

List 深拷貝

如圖,深拷貝就是將A複製給B的同時,給B創建新的地址,再將地址A的內容傳遞到地址B。ListA與ListB內容一致,但是由於所指向的地址不同,所以改變相互不受影響。

深拷貝的方法
使用序列化方法

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中的對象(如果對象中的屬性有對象也算)都要序列化:

public class Person implements Serializable{
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章