我的问题是我有一个名为currentComponents的初始列表。我将其项目复制到另一个名为currentMonitorComponents的新列表中。但是,当currentMonitorComponents中的组件被自动修改时,currentComponents列表中的项目也会被修改。我的代码是这样的-

 List<MonitorComponent> currentMonitorComponents = new ArrayList<MonitorComponent>();
        currentMonitorComponents.addAll(currentComponents);

最佳答案

您必须复制一份清单:

 ArrayList<MonitorComponent> currentComponentsClone = new ArrayList<MonitorComponent>();
 for(MonitorComponent m : currentMonitorComponents)
    currentComponentsClone.add(m.clone());


并在您的课程中实现clone方法:

public class MonitorComponent{

    String s;
    Date d;
    ...

    public MonitorComponent clone(){
        MonitorComponent m = new MonitorComponent();
        m.s = this.s.clone();
        m.d = this.d.clone();
        ...
        return m;
    }
}

09-16 03:30