ArrayList的深层副本

时间:2020-05-06 01:06:57

标签: java

我需要为存取器和更改器方法制作一个长类型的ArrayList的深层副本。我已经尝试进行搜索,但是无论我发现和尝试什么,我的测试都表明,mutator没有深度复制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;
    }

那不正确吗?

2 个答案:

答案 0 :(得分:0)

在添加对象之前将其克隆。例如,代替newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

假设clone中的Person被正确覆盖。

答案 1 :(得分:0)

长是不可变的,因此您不必担心克隆它们。

List<Long> transactions = Arrays.asList(1L, 2L, 3L, 4L);

List<Long> copy = new ArrayList<>(transactions);
相关问题