My question is very basic but I am still not able to figure out how to do this. I have an array of ArrayList like this:
ArrayList<Car>[] cars = new ArrayList[2];
Later in my program I am iterating over that array and I need to remove some objects from the ArrayList. However, since I cannot iterate over a list and remove the elements at the same time, I have decided to clone the array and remove the objects from the ArrayList of the clone. I noticed though, that the clone is referencing the same objects as the ones from the array. Below is some basic example:
ArrayList<Car>[] cars = new ArrayList[2];
cars[0] = new ArrayList<Car>();
cars[0].add(new Car("black"));
cars[0].add(new Car("white"));
cars[1] = new ArrayList<Car>();
cars[1].add(new Car("green"));
cars[1].add(new Car("red"));
ArrayList<Car>[] carClone = cars.clone();
carClone[0].remove(0); // removes the objects from the ArrayList of clone as well as the ArrayList of the "real" array
In the above example you can see that it doesn't just remove the object from the clone, but also from the array. How can I overcome this problem? Any thoughts?