Java克隆执行深拷贝
示例
要复制嵌套对象,必须执行深层复制,如本示例所示。
import java.util.ArrayList; import java.util.List; public class Sheep implements Cloneable { private String name; private int weight; private List<Sheep> children; public Sheep(String name, int weight) { this.name= name; this.weight= weight; } @Override public Object clone() throws CloneNotSupportedException { Sheep clone = (Sheep) super.clone(); if (children != null) { // 深拷贝 List<Sheep> cloneChildren = new ArrayList<>(children.size()); for (Sheep child : children) { cloneChildren.add((Sheep) child.clone()); } clone.setChildren(cloneChildren); } return clone; } public List<Sheep> getChildren() { return children; } public void setChildren(List<Sheep> children) { this.children= children; } } import java.util.Arrays; import java.util.List; Sheep sheep = new Sheep("Dolly", 20); Sheep child1 = new Sheep("Child1", 4); Sheep child2 = new Sheep("Child2", 5); sheep.setChildren(Arrays.asList(child1, child2)); // 克隆sheep Sheep dolly = (Sheep) sheep.clone(); List<Sheep> sheepChildren = sheep.getChildren(); List<Sheep> dollysChildren = dolly.getChildren(); for (int i = 0; i < sheepChildren.size(); i++) { // 打印false,两个数组都包含内部对象的副本 System.out.println(sheepChildren.get(i) == dollysChildren.get(i)); }