0

i got a problem with hashset, I cannot remove a hashset, and here is the code

//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);                       
            }
        }
    }

But, it gives me an exception, it says like :

Exception in thread "main" java.util.ConcurentModificationException, could anyone help me? thanks :)

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
user2186299
  • 71
  • 1
  • 11

2 Answers2

2

This is because the foreach loop (for (Whatever x: something)) internally creates an Iterator.

And when you remove from the Iterable (the something above) being iterated, a well-behaved Iterator will detect that "hey, you have modified my babies beyond my knowledge" and throw this exception.

What you should do is this:

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
}
fge
  • 119,121
  • 33
  • 254
  • 329
0

you are performing a concurrent modification - you are iterating over a collection and modifiying it not by the iterator, you should transform your code to this:

for (Iterator<String> it = streams.iterator(); it.hasNext();) {
    String word = it.next();
    for (String sw : stopWords) {
        if (word.equals(sw)) {
            it.remove();
            break;
        }
    }
}
bennyl
  • 2,886
  • 2
  • 29
  • 43