如何复制数组列表以不反映原始列表中的更改? [英] How to copy an arraylist to not reflecting changes in the original list?

查看:107
本文介绍了如何复制数组列表以不反映原始列表中的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将列表复制到另一个列表,并对新列表中包含的对象进行更改,而不影响旧列表中的对象?

How can I copy a list to another list, and make changes to the objects contained in the new list, without affecting the objects in the old list?

class Foo {
   String title;
   void setTitle(String title) { this.title = title; }
}

List<Foo> original;
List<Foo> newlist = new ArrayList<Foo>(original);

for (Foo foo : newlist) {
   foo.setTitle("test"); //this will also affect the objects in original list.
                         //how can I avoid this?
}


推荐答案

对象,但是你必须实现一个克隆方法才能工作。换句话说,没有一个简单的,一般的交钥匙解决方案。

You will have to clone the objects, but then you have to implement a clone method for it to work. In other words, there is not a simple, general turnkey solution.

List<Foo> original;
List<Foo> newList=new ArrayList<Foo>();

for (Foo foo:original){
    newList.add(foo.clone();
}

//Make changes to newList

在列出的案例中,克隆可以是:

In the listed case clone could be:

class Foo {

    String title;

    void setTitle(String title) { this.title = title; }

    Foo clone(Foo foo){
        Foo result=new Foo();
        result.setTitle(foo.title);
        return result;
    }
}

这篇关于如何复制数组列表以不反映原始列表中的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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