使用序列化流实现对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'}