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

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

问题描述

我一直在我的一个项目中使用 ArrayLists,我需要创建一个默认的 ArrayList,这样我就可以随时重置原始的.所以,我复制了原来的 ArrayList 来创建默认的.但是,每当我修改原始内容时,它也会更改默认值.如何使副本静态"且不可更改?

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();
    }

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

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".

推荐答案

clone() for ArrayLists 应该避免,因为即使它创建一个新的List 实例,它拥有相同的元素.因此,在第一个 List 上更改的元素也将在第二个上更改.拥有相同引用的两个不同对象.

clone() for ArrayLists should be avoided because even if it creates a new List instance, it holds the same elements. So an element changed on the first List will also be changed on the second one. Two different objects holding the same references.

下面的代码将使用新元素创建一个新实例.

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

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

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

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