无法删除java中的hashset

时间:2014-03-22 12:26:10

标签: java

我的hashset有问题,我无法删除哈希集,这里是代码

//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,有人可以帮帮我吗?谢谢:))

2 个答案:

答案 0 :(得分:2)

这是因为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
}

答案 1 :(得分:0)

您正在执行并发修改 - 您正在迭代集合并且不是通过迭代器修改它,您应该将代码转换为:

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