【发布时间】:2014-04-07 03:57:12
【问题描述】:
我如何复制包含 ArrayList 成员的对象的 ArrayList。也有可能,列表中对象的成员还包含ArrayList 成员,依此类推。那么有没有一种通用的方法来复制对象列表而不考虑其成员?
为所有涉及的对象实现Clone Interface 似乎不是一个好主意,因为I read that its broken。
我创建了一个小型 SSCCE 来举例说明我的问题:
class Foobar {
public List<String> listMember;
public String primitiveMember;
public Foobar() {
listMember = new ArrayList<String>(Arrays.asList("a", "b", "c"));
primitiveMember = "testABC";
}
}
// Create list of Foobar
List<Foobar> foobars = new ArrayList<Foobar>();
foobars.add(new Foobar());
// Copy list of Foobar
List<Foobar> foobarsCopy = new ArrayList<Foobar>();
foobarsCopy.add(null);
Collections.copy(foobarsCopy, foobars);
// Modify source list
foobars.get(0).listMember.add("-1-");
// Output of references
System.out.println("Sourcelist has size of: " + foobars.get(0).listMember.size());
System.out.println("Destinationlist has size of: " + foobarsCopy.get(0).listMember.size());
System.out.println("Function 'Collections.copy(...) does not copy list members of members?: " + (foobars.get(0).listMember.size() == foobarsCopy.get(0).listMember.size()) + " - References: " + foobars.get(0).listMember.hashCode() + " vs " + foobarsCopy.get(0).listMember.hashCode());
【问题讨论】:
标签: java object arraylist clone