Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何制作Java ArrayList的深度副本_Java_Arraylist_Deep Copy - Fatal编程技术网

如何制作Java ArrayList的深度副本

如何制作Java ArrayList的深度副本,java,arraylist,deep-copy,Java,Arraylist,Deep Copy,可能重复: 正在尝试制作ArrayList的副本。底层对象很简单,包含字符串、整数、大小数、日期和日期时间对象。 如何确保对新ArrayList所做的修改不会反映在旧ArrayList中 Person morts = new Person("whateva"); List<Person> oldList = new ArrayList<Person>(); oldList.add(morts); oldList.get(0).setName("Mortimer");

可能重复:

正在尝试制作ArrayList的副本。底层对象很简单,包含字符串、整数、大小数、日期和日期时间对象。 如何确保对新ArrayList所做的修改不会反映在旧ArrayList中

Person morts = new Person("whateva");

List<Person> oldList = new ArrayList<Person>();
oldList.add(morts);
oldList.get(0).setName("Mortimer");

List<Person> newList = new ArrayList<Person>();
newList.addAll(oldList);

newList.get(0).setName("Rupert");

System.out.println("oldName : " + oldList.get(0).getName());
System.out.println("newName : " + newList.get(0).getName());
Person morts=新人(“whateva”);
List oldList=new ArrayList();
添加(morts);
oldList.get(0).setName(“摩梯末”);
List newList=newarraylist();
newList.addAll(oldList);
newList.get(0).setName(“Rupert”);
System.out.println(“oldName:+oldList.get(0.getName());
System.out.println(“newName:+newList.get(0.getName());
干杯,
P

在添加对象之前克隆对象。例如,代替

newList.addAll(oldList)

假设在
Person
中正确覆盖了
clone

public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}
在执行代码中:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());
ArrayList clone=new ArrayList();
for(个人p:原创者)
clone.add(p.clone());

Java是通过引用传递的。因此,最初在两个列表中都有“相同”的对象引用……您需要使用
clone()
方法。好吧,每件事你都得打电话separately@Wulf
String
不是中的基本数据类型Java@ataulm字符串在Java中是不可变的。因为您无法更改它们,所以克隆它们没有意义。“克隆没有意义”不同于“您不能克隆”是的,克隆是浅拷贝,在克隆()之后,Person对象中的成员仍然是相同的引用,因此您需要根据需要重写clone方法,而不需要假设重写,默认的
clone()
受保护。
ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());