【发布时间】:2012-02-13 11:24:14
【问题描述】:
我有一个ArrayList<Widget>,我想“深入”克隆,以便对原始列表中的任何项目进行修改不会对克隆列表中的项目产生任何影响:
ArrayList<Widget> origList = getMyList();
ArrayList<Widget> cloneList = origList.clone();
// Remove the 5th Widget from the origina list
origList.remove(4);
// However, the cloneList still has the 5th Widget and is unchanged
// Change the id of the first widget
origList.get(0).setId(20);
// However in cloneList, the 1st Widget's ID is not 20
实现此目的最好/最安全的方法是什么?我想它并不像这样简单:
ArrayList<Widget> cloneList = origList.clone();
我想这是一个内置的ArrayList 类型,再加上它的泛型这一事实会使事情复杂化。我还想我需要为我的Widget 类编写一个特殊的clone() 覆盖?
提前致谢!
编辑:
如果有一个公共 JAR 可以为我完成这项繁重的工作,我也会完全接受,所以请随时提出建议,但是我仍然想知道如何以旧时尚的方式做到这一点,所以我可以学习;-)
【问题讨论】:
-
发帖前请先搜索