如何将列表复制到另一个列表,并更改新列表中包含的对象,而不影响旧列表中的对象?
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?
}
Run Code Online (Sandbox Code Playgroud)
您将不得不克隆对象,但是您必须实现克隆方法才能使用它.换句话说,没有简单的通用交钥匙解决方案.
List<Foo> original;
List<Foo> newList=new ArrayList<Foo>();
for (Foo foo:original){
newList.add(foo.clone();
}
//Make changes to newList
Run Code Online (Sandbox Code Playgroud)
在列出的案例中,克隆可以是:
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;
}
}
Run Code Online (Sandbox Code Playgroud)