Monday, 15 September 2014

java - Getting ConcurrentModifcationException even while iterating using iterator -



java - Getting ConcurrentModifcationException even while iterating using iterator -

this question has reply here:

concurrentmodificationexception arraylist [duplicate] 6 answers

i have next method:

//cleans stop words @ origin of sentence, returns remaining //sentence. public static string cleanbeginning(string sentence, boolean skipempty) { list<string> words = common.getwords(sentence, skipempty); int = 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(); (string cleanedword : words) { sb.append(cleanedword ).append(" "); } homecoming sb.tostring().trim(); }

on line: string word = iterator.next();

i java.util.concurrentmodificationexception. why that? thought iterator.next() supposed safe way loop on arraylist? doing wrong?

you need remove collection using iterator, , you're not doing that.

change:

words.remove(i);

to:

iterator.remove();

java

No comments:

Post a Comment