Do you decrease the counter in a for loop after removing the ArrayList element?

advertisements

Do you decrement the counter variable in a for loop after removing an ArrayList element? If so, is this because the list shifts left? I have provided my code, which seems to work:

public void removeLine(String ln)
{
  //loop through lineList
  for (int i = 0; i < lineList.size(); i++)
  {
    //check if match is found
    if (lineList.get(i).equals(ln))
    {
      //remove element at i
      lineList.remove(i);

      //decrement i
      i--;
    } //end if
  } //end for
} //remove line


Yes you have to decrement it, or it'll skip over the next entry.

Alternatively, I prefer to not increment if an item is removed. Like this:

public void removeLine(String ln)
{
  //loop through lineList
  for (int i = 0; i < lineList.size(); /**/)
  {
    //check if match is found
    if (lineList.get(i).equals(ln))
    {
      //remove element at i
      lineList.remove(i);
      continue;
    }

    ++i;
  }
}