I am implementing logic within a for-loop
that will remove any dog objects with status "ACCEPTED" from a kennel Object.
Note that a Kennel can have a List of many dogs.
Loop:
allDogsInKennel = kennel.getDogsList();
for (int i = 0; i < allDogsInKennel.size(); i++) {
//delete any dog object with a status of Accepted
if (allDogsInKennel.get(i).getStatus() == "ACCEPTED") {
kennel.removeDog(allDogsInKennel.get(i));
}
}
removeDog method
public void removeDog(Dog d) {
this.dogList.remove(d);
}
The problem I have is e.g. all 6
dogs in the list should be removed, but at present only 3
are being removed.
Example:
original size of list = 6 items
Item removed from index 0 = 5 items
Item removed from index 1 = 4 items
item removed from index 2 = 3 items
Now in the next iteration the loop tries to remove from index 3
due to i++
condition, but the array will only go to index 2
as it now has only 3
items at indexes:
0, 1, 2
How can I change my logic above to ensure that all items are removed from the array?