java 类的复制,分为深度复制,和浅复,
在一个类中有其他的类型,可改变的类eg:List,只是复写Object clone,只是浅复制,
需要对类中有其他的类型也需要复制,这样才是深复制
package com.example.sperson.web;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Demo implements Cloneable {
public String name;
public List<String> list;
public Demo(String name, List<String> list) {
this.name = name;
this.list = list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Demo demo = (Demo) super.clone();
demo.list = new ArrayList<>();
demo.list.addAll(this.list);
return demo;
}
}
public class test {
public static void main(String[] args) throws CloneNotSupportedException {
List<String> list = Arrays.asList("sdllfslflks".split(""));
Demo demo = new Demo("demo", list);
System.out.println(demo.getList().size());
Demo demo1 = (Demo) demo.clone();
demo1.getList().add("sdsdsd");
System.out.println(demo1.getList().size());
}
}
参考
https://www.cnblogs.com/acode/p/6306887.html