如何制作 Java ArrayList 的深拷贝 [英] How to make a deep copy of Java ArrayList

查看:31
本文介绍了如何制作 Java ArrayList 的深拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何克隆 ArrayList 并克隆其内容?

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

trying to make a copy of an ArrayList. The underlying object is simple containing on Strings, ints, BigDecimals, Dates and DateTime object. How can I ensure that the modifications made to new ArrayList are not reflected in the old 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());

干杯,

推荐答案

在添加对象之前先克隆它们.例如,代替 newList.addAll(oldList);

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

假设 clonePerson 中被正确覆盖.

Assuming clone is correctly overriden inPerson.

这篇关于如何制作 Java ArrayList 的深拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆