如何复制不受原始ArrayList更改影响的ArrayList? [英] How to copy an ArrayList that cannot be influenced by the original ArrayList changes?

查看:309
本文介绍了如何复制不受原始ArrayList更改影响的ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在我的一个项目上使用ArrayLists,我需要创建一个默认的ArrayList,以便可以随时重置原始列表。因此,我复制了原始的ArrayList来创建默认的ArrayList。但是,每当我修改原始文件上的内容时,它也会更改默认文件。我如何使副本静态且不可更改?



这是我的代码:(用葡萄牙语)

  private ArrayList< Compartimento> listaCompartimentos; 
private ArrayList< Compartimento> listaCompartimentosDEFAULT;

public Simulador(){
this.listaCompartimentos = new ArrayList<>();
this.listaCompartimentosDEFAULT = new ArrayList<>();
}

//数组的复制
public void gravarListaDefault(){
this.listaCompartimentosDEFAULT =(ArrayList< Compartimento>)listaCompartimentos.clone();
}

注意:我不知道这可能是其背后的原因,但是ArrayList listaCompartimentos具有listaEquipamentos。对于每个 Compartimento,都有一个ArrayList listaEquipamentos。

解决方案

克隆表示您有2个不同的列表,但是它们的内容是相同。如果更改第一个列表中的对象的状态,则它将在第二个列表中更改。



使用复制构造函数,并避免 clone()



应该避免为数组列表使用 new ArrayList(originalList)



Clone(),因为即使创建了新实例,其中包含相同元素。因此,在列表上更改的元素将在第二个元素上更改。



下面的代码将创建带有新元素的新实例。

  ArrayList< Object> clone =新的ArrayList< Object>(); 
for(对象o:originalList)
clone.add(o.clone());


I've been using ArrayLists on a project of mine, and I need to create a default ArrayList so I can reset the original one whenever I want. So, I copy the original ArrayList to create the default one. However, whenever I modify something on the original, it also changes the default one. How can I make the copy "static" and unchangeable?

Here is my code: (It's in portuguese)

private ArrayList<Compartimento> listaCompartimentos;
private ArrayList<Compartimento> listaCompartimentosDEFAULT;

public Simulador() {
        this.listaCompartimentos = new ArrayList<>();
        this.listaCompartimentosDEFAULT=new ArrayList<>();
    }

//Copy of the array
public void gravarListaDefault(){
        this.listaCompartimentosDEFAULT=(ArrayList<Compartimento>)listaCompartimentos.clone();
    }

Note: I don't know if it can be the reason behind it, but the ArrayList listaCompartimentos has a listaEquipamentos. For each "Compartimento" there is an ArrayList "listaEquipamentos".

解决方案

Cloning means you have 2 different lists, but their contents are the same. If you change the state of an object inside the first list, it will change in the second list.

Use the copy-constructors and avoid clone() :

new ArrayList(originalList)

Clone() for arraylists should be avoided because even if it creates a new instance, it holds the same elements. So an element which is changed on a list will be changed on the second one.

The code below will create a new instance with new elements.

ArrayList<Object> clone = new ArrayList<Object>();
for(Object o : originalList)
clone.add(o.clone());

这篇关于如何复制不受原始ArrayList更改影响的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆