ArrayList.remove()

ArrayList.remove()

我的项目中有三个 classes。其中之一是 class Main,它包含来自 class 操作的对象的 ArrayList。最后一个class是Algorithm,里面也包含Operation对象的ArrayList。我的问题是,当我从一个列表中删除对象时,它也会从另一个列表中删除。我不知道为什么,有什么提示吗?这是代码的一部分:

class Main{
    static ArrayList<Operation> operations = new ArrayList<>();
    ...
    public static void main(String args[]){
        Algorithm algorithm = new Algorithm();
        algorithm.mrowkowy();
    }

class Algorithm{
    ArrayList<Operation> operations_temp = Main.operations;
    ...
    mrowkowy(){
        ...
        Operation Actual = new Operation();
        operations_temp.remove(Actual);
    }

改变

ArrayList<Operation> operations_temp = Main.operations;

ArrayList<Operation> operations_temp = (ArrayList<Operation>)Main.operations.clone();

或更好

  List<Operation> operationsTemp = new ArrayList<>(Main.operations);
//↑                         ⬑use camelCase in Java
//└─────prefer to work on interfaces to increase flexibility of code 

根据您的操作,这两个对象是相同的,因此移除一个对象实际上就是移除另一个对象。通过调用 .clone(),您正在创建一个新的对象列表,当从中删除对象时,不会从父对象中删除相应的键。