1

I have the following method:

//Cleans any stop words at the beginning of the sentence, returns the remaining
//sentence.
public static String cleanBeginning(String sentence, boolean skipEmpty)
{
    List<String> words = Common.getWords(sentence, skipEmpty);
    int i = 0;
    Iterator<String> iterator = words.iterator();
    while (iterator.hasNext() )
    {
        String word = iterator.next();
        if ( stopWords.contains( word.toLowerCase() ) )
        {
            words.remove(i);
            continue;
        }
        break;
    }

    StringBuilder sb = new StringBuilder();
    for (String cleanedWord : words)
    {
        sb.append(cleanedWord ).append(" ");
    }

    return sb.toString().trim();
}

On the line: String word = iterator.next();

I get a java.util.ConcurrentModificationException. Why is that? I thought iterator.next() was supposed to be a safe way to loop over an arraylist? Am i doing anything wrong?

Ali
  • 261,656
  • 265
  • 575
  • 769
  • 4
    Just iterating using an iterator isn't enough. You have to make your changes through it too. – awksp Jun 24 '14 at 02:25

1 Answers1

4

You need to remove from the collection using the iterator, and you're not doing that.

Change:

words.remove(i);

to:

iterator.remove();
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373