[英]Deep copy of ArrayList
我需要为访问器和修改器方法制作一个 long 类型的 ArrayList 的深层副本。 我试图搜索这个,但无论我找到什么并尝试,我的测试表明突变器没有深度复制 ArrayList。 这个 ArrayList 被称为“事务”,它包含在“CustomerData”的子类中,该子类是“PersonData”。
这是我的突变器:
public ArrayList<Long> getTransactions() {
if (transactions == null) throw new IllegalArgumentException();
final ArrayList<Long> copy = new ArrayList<Long>(transactions.size());
for(Long l : transactions) {
copy.add(new Long(l.intValue()));
}
return copy;
}
不正确怎么办?
在添加对象之前克隆对象。 例如,而不是newList.addAll(oldList);
for(Person p : oldList) {
newList.add(p.clone());
}
假设clone
在Person
中被正确覆盖。
Long 是不可变的,因此您不必担心克隆它们。
List<Long> transactions = Arrays.asList(1L, 2L, 3L, 4L);
List<Long> copy = new ArrayList<>(transactions);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.