2

古いリストのオブジェクトに影響を与えずに、リストを別のリストにコピーし、新しいリストに含まれるオブジェクトを変更するにはどうすればよいですか?

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?
}
4

2 に答える 2

8

オブジェクトのクローンを作成する必要がありますが、それを機能させるにはクローン メソッドを実装する必要があります。つまり、単純で一般的なターンキー ソリューションはありません。

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

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

//Make changes to newList

リストされている場合、クローンは次のようになります。

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;
    }
}
于 2013-04-03T21:24:58.450 に答える
3

次のように試すことができます。

public ArrayList<Foo> deepCopy(ArrayList<Foo> obj)throws Exception
{
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(baos);
  baos.writeObject(obj);
  oos.close();
  ByteArrayInputStream bins = new ByteArrayInputStream(baos.toByteArray());
  ObjectInputStream oins = new ObjectInputStream(bins);
  ArrayList<Foo> ret =  (ArrayList<Foo>)oins.readObject();
  oins.close();
  return ret;
}
于 2013-04-03T21:23:42.647 に答える