Java 即使在使用迭代器进行迭代时也获取ConcurrentModificationException

Java 即使在使用迭代器进行迭代时也获取ConcurrentModificationException,java,Java,我有以下方法: //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

我有以下方法:

//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();
}
//清除句子开头的所有停止词,返回剩余的
//判决。
公共静态字符串开头(字符串语句,布尔值skipmpty)
{
List words=Common.getWords(句子,skipEmpty);
int i=0;
迭代器迭代器=words.Iterator();
while(iterator.hasNext())
{
String word=iterator.next();
if(stopWords.contains(word.toLowerCase()))
{
删除(i)段;
继续;
}
打破
}
StringBuilder sb=新的StringBuilder();
for(字符串清除字:字)
{
附加(干净的词)。附加(“”);
}
使某人恢复原状;
}
在线:
String word=iterator.next()


我得到一个
java.util.ConcurrentModificationException
。为什么呢?我认为
iterator.next()
应该是在arraylist上循环的安全方法?我做错了什么吗?

您需要使用迭代器从集合中删除,但您没有这样做

更改:

words.remove(i);
致:


您需要使用迭代器从集合中删除,但您没有这样做

更改:

words.remove(i);
致:


仅仅使用迭代器进行迭代是不够的。您也必须通过它进行更改。仅使用迭代器进行迭代是不够的。您也必须通过它进行更改。谢谢!“我总是忘记做这件事。”点击投票:不客气。谢谢!“我总是忘记做这件事。”点击投票:不客气。