无法在java中删除哈希集



我有一个问题与哈希集,我不能删除哈希集,这里是代码

//take stopword list from file    
public void stopWordList(){
    openFile("D:/ThesisWork/Perlengkapan/stopword.txt");
    while(x.hasNext()){
        String a = x.nextLine();    
        a = a.toLowerCase();    
        stopWords.add(a);
    }
}
    //the method to remove stopword
public void stopWordRemoval(){
    stopWordList();
            //if the word in the streams set is equal to stopword, it should be removed
    for(String word:streams){
        for(String sw:stopWords){
            if(word.equals(sw)){
                streams.remove(word);                       
            }
        }
    }

但是,它给我一个异常,它说:

Exception in thread "main" java.util.ConcurentModificationException,有人能帮我吗?谢谢:)

这是因为foreach循环(for (Whatever x: something))内部创建了一个Iterator

当你从正在迭代的Iterable(上面的something)中移除时,一个表现良好的Iterator将检测到"嘿,你已经在我的知识范围内修改了我的婴儿"并抛出此异常。

你应该这样做:

final Iterator<String> iterator = stream.iterator();
String word;
while (iterator.hasNext()) {
    word = iterator.next();
    if (stopWords.contains(word))
        iterator.remove(); // This is safe: an iterator knows how to remove from itself
}

如果你正在执行一个并发修改——你在一个集合上迭代,而不是通过迭代器修改它,你应该把你的代码转换成这样:

for (Iterator<String> it = streams.iterator(); it.hasNext();) {
    String word = it.next();
    for (String sw : stopWords) {
        if (word.equals(sw)) {
            it.remove();
            break;
        }
    }
}

最新更新