工作中经常需要用到一份拷贝的数据进行加工、处理、聚集扩充,而不影响原数据。
简单的实现方式介绍一种,
序列化实现:
对象(必须序列化):
public class Human implements Serializable{
@Getter @Setter
private Integer age;
@Getter @Setter
private String name;
public Human(Integer age, String name){
this.age = age;
this.name = name;
}
public static int compareByNameThenAge(Human h1, Human h2){
return h1.getAge().compareTo(h2.getAge());
}
}
示例:
List<Human> humanList = new ArrayList<>();
Human human = new Human(18, "sasa");
Human human2 = new Human(20, "huihui");
humanList.add(human);
humanList.add(human2);
// 浅拷贝
List<Human> copyHumanList = new ArrayList<>(humanList);
// 深拷贝
List<Human> copyDeepHumanList = new ArrayList<>(humanList.size());
for(Human origin : humanList){
copyDeepHumanList.add((Human)SerializationUtils.clone(origin));
}
System.out.println("origin:" + humanList.get(1).getAge()); // origin:20
System.out.println("copy:" + copyHumanList.get(1).getAge()); // copy:20
System.out.println("copy deep:" + copyDeepHumanList.get(1).getAge()); // copy deep:20
// 数据变动
copyHumanList.get(1).setAge(25);
System.out.println("origin:" + humanList.get(1).getAge()); // origin:25
System.out.println("copy:" + copyHumanList.get(1).getAge()); // copy:25
System.out.println("copy deep:" + copyDeepHumanList.get(1).getAge()); //copy deep:20
主要使用了org.apache.commons.lang.SerializationUtils
JSON方式:
public static <T> Set<T> clone(Set<T> original) {
Gson gson = new Gson();
// Convert the Set to JSON String
String jsonString = gson.toJson(original);
// Convert the JSON String back to new Set Object and return it
Set<T> copy = gson.fromJson(jsonString, Set.class);
return copy;
}