即使在使用迭代器进行迭代时也会获得ConcurrentModifcationException

时间:2014-06-24 02:23:35

标签: 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 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();
}

在线: String word = iterator.next();

我得到java.util.ConcurrentModificationException。这是为什么?我认为iterator.next()应该是一种安全的方式来绕过一个arraylist?我做错了吗?

1 个答案:

答案 0 :(得分:4)

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

变化:

words.remove(i);

为:

iterator.remove();