Not entirely sure what you are trying to do here, but I think you want to remove elements such that there are no two string with length > 1
in a row. While the general advice to loop the list in reverse order is sound, there might be reasons to loop the list in the right order.
Your idea with using i--
after removing an element was correct. But you have to do it in all cases, not only if you are not on the first element. Remove the if
, then it should work.
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i).length() > 1 && list.get(i + 1).length() > 1) {
list.remove(i+1);
i--;
}
}
If i == 0
, this will set i
to -1
, which may seem odd, but remember that i++
will set it back to 0
before the next iteration of the loop. So for 11, 22, 33
, it will first compare 11
and 22
, then remove 22
, and continue comparing 11
and 33
(and remove 33
and so forth).