Let's say we have an ArrayList of Cats.
This is our cat:
public class Cat{
String color;
int age;
public Cat(String color, int age){
this.color = color;
this.age = age;
}
}
We have a cat and each cat has a color. Somewhere else in our code, we have the following:
ArrayList<Cat>cats = new ArrayList<Cat>();
cats.add(new Cat("white",5);
cats.add(new Cat("black",6);
cats.add(new Cat("orange",10);
cats.add(new Cat("gray",3);
System.out.println(cats.size()); prints out 4
So now are cats ArrayList has 4 cats in it. What if I want to remove all cats that are over 5 years old, shouldn't I be able to do the following?
for(int index = 0; index<cats.size(); index++){
if(cats.get(index).age > 5){
cats.remove(index);
}
}
Now after that runs, I print out the size of the cats ArrayList and it says 3, even though it should remove 3 Cats and leave one.
So, shouldn't this work? I don't understand why it wouldn't. What other ways are there to remove objects with specific values from a List/Array?