使用序列化流實現對List泛型的深拷貝
深拷貝
- 爲新的對象重新開闢一個內存空間,拷貝原有對象的數據結構和值;新的對象的值修改不會涉及原對象的值(請注意性能問題)。
實現序列化拷貝的前提條件
-
實體對象實現Serializable接口
/** * 用戶實體類 */ public class UserEntity implements Serializable { private int id; private String username; private String sex; private int age; private String address; private String birthday; //get、set方法省略 public UserEntity(int id, String username, String sex, int age, String address) { this.id = id; this.username = username; this.sex = sex; this.age = age; this.address = address; } @Override public String toString() { return "UserEntity{" + "id=" + id + ", username='" + username + '\'' + ", sex='" + sex + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; } }
序列化拷貝方法
-
private static final Logger LOGGER = LoggerFactory.getLogger(DeepCopyDemo.class); public static <T> List<T> deepCopy(List<T> list) { //判斷是否實現序列化 if (list instanceof Serializable){ ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); try { ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(list); ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream inStream = new ObjectInputStream(byteIn); List<T> ts = (List<T>) inStream.readObject(); return ts; } catch (Exception e) { LOGGER.error("序列化Copy失敗", e); e.printStackTrace(); } } return null; }
序列化拷貝測試
-
public static Integer INDEX = 0; public static void main(String[] args) { UserEntity userEntity1 = new UserEntity(0, "張無忌","女",1 , "beijignshi"); UserEntity userEntity2 = new UserEntity(1, "李尋歡","女",4 , "tianjinshi"); UserEntity userEntity3 = new UserEntity(3, "項羽","男",0 , "chuguo"); UserEntity userEntity4 = new UserEntity(4, "劉邦","男",8 , "hanchao"); List<UserEntity> list = new ArrayList<>(); list.add(userEntity2); list.add(userEntity1); list.add(userEntity4); list.add(userEntity3); System.out.println("----deep copy front----"); for (UserEntity userEntity: list) { System.out.println(userEntity.toString()); } List<UserEntity> copyResult = deepCopy(list); System.out.println("----deep copy after----"); copyResult.get(INDEX).setUsername("夷陵老祖"); for (UserEntity userEntity: copyResult) { System.out.println(userEntity.toString()); } }
拷貝結果
-
----deep copy front---- UserEntity{id=1, username='李尋歡', sex='女', age=4, address='tianjinshi'} UserEntity{id=0, username='張無忌', sex='女', age=1, address='beijignshi'} UserEntity{id=4, username='劉邦', sex='男', age=8, address='hanchao'} UserEntity{id=3, username='項羽', sex='男', age=0, address='chuguo'} ----deep copy after---- UserEntity{id=1, username='夷陵老祖', sex='女', age=4, address='tianjinshi'} UserEntity{id=0, username='張無忌', sex='女', age=1, address='beijignshi'} UserEntity{id=4, username='劉邦', sex='男', age=8, address='hanchao'} UserEntity{id=3, username='項羽', sex='男', age=0, address='chuguo'}