The issue here is that when you do a.remove(i);
, the ArrayList automatically updates its indices, so you end up skipping a value. Here's an example of how this could happen:
- You get the 1st element (
a.get(0);
)
- You find that it is an even length string (
wordEntry.length() % 2 == 0
)
- You remove it (
a.remove(i);
)
- Your for loop advances to the next value (now i = 1)
- You get what is now the 2nd element (
a.get(1);
), but because you removed what was the 1st element, this is now what used to be the 3rd element.
In this scenario, you skipped over that 2nd element, which is why some strings are slipping through unnoticed. This is where I would suggest using the enhanced for loop, which simplifies things significantly so you don't need to worry about what index you are on. It would look something like this:
public ArrayList<String> removeEvenLength(ArrayList<String> a) {
for (String wordEntry : a) {
if (wordEntry.length() % 2 == 0) {
a.remove(wordEntry);
}
}
return a;
}
Alternatively, if you want to go for an even simpler one-liner, ArrayList offers some very convenient methods for manipulating ArrayLists. One such method, called removeIf(), pretty much does exactly what you want, but I think it's good to learn to properly use for loops before going on to use built-in methods like this. That said, if you wanted to go that route, here's how I would do it:
public ArrayList<String> removeEvenLength(ArrayList<String> a) {
a.removeIf((wordEntry) -> wordEntry.length() % 2 == 0);
return a;
}
Also, I just felt that I should note that there are other ways of finding even numbers. You can also use (wordEntry.length() & 1) == 0
. There's no real difference as far as performance or anything, it's really just personal preference, but I just felt I should mention another way of doing it :)