-1

I have three classes in my project. One of them is class Main, which contain ArrayList of objects from class Operation. The last one class is Algorithm, which also contain ArrayList of objects from Operation. My problem is, when I remove object from one List it also removes from another. I don't know why, any hints? Here is the part of the code:

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);
    }
Umur Kontacı
  • 35,403
  • 8
  • 73
  • 96
user3541098
  • 109
  • 7

1 Answers1

0

Change

ArrayList<Operation> operations_temp = Main.operations;

to

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

or better

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

With what you're doing, the two objects are the same, and thusly removing one is essentially removing the other. By calling .clone(), you're creating a new list of Objects which when removed from, will not remove the corresponding key from the parent.

Arhowk
  • 901
  • 4
  • 11
  • 22
  • 3
    `clone` returns Object so you also need to cast it. But better don't even use clone since [it is not best choice](http://www.artima.com/intv/bloch13.html). Instead prefer copy-constructor, which will also let you avoid compilation warnings, and will let you use abstraction (`List`) instead of actual implementation [which is also preferable](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface). – Pshemo Jan 10 '15 at 01:32
  • @Pshemo When I wrote that, it hadn't been corrected -- All that was there was the suggestion to `clone()` it. Also, one of the characters you used isn't showing up properly on my screen; it's the one just before `use campelCase` (which is misspelled btw) – Nic Jan 10 '15 at 02:39