I’ have very unusual problem with removing elements from List.
Here is my code:
for (int i = 0; i < offers.size(); i++) {
if(offers.get(i).isSpecialOffer()){
offers.remove(i);
}
}
return offers;
When I print out offers for testing, I get the right result everyone is true. But when I try to remove elements with true boolean I get wrong result. It prints out offers with false boolean.
I dont know where is the problem?
Thanks for help
UPDATE:
I have function for removing specialOffers from List. I’ always get some offers with true value.
If you include the
remove(which is currently commented out) before you use theSystem.out.printlncall, then you’ll be printing out a different value to the one you remove. For example:Before removal:
Now if
iis one, we’ll callremove(1), leaving… so we’ve removed
Bar, and then we’d printBazYou’ll also then not check
Baz, as you’d incrementito 2 before testing again.To do this sort of thing properly, you should either use a loop like this:
Or if you really want to use the index, ideally work backwards to avoid problems: