I have a problem with iterator remove which is causing IllegalStateException. The error is occurring in
depIterator.remove() I'm not sure why this is occurring. Any help would be appreciated.
List<Dependency> listofAllDependency = new ArrayList<Dependency>();
while(!dependencyTable.isEmpty()){
//allValuesDependentsAreBuilt = false;
Iterator<Entry<Dependency, List<Dependency>>> depIterator = dependencyTable.entrySet().iterator();
while(depIterator.hasNext()){
ArrayList<String> allValuesDependentsAreBuilt = new ArrayList<String>();
Entry<Dependency, List<Dependency>> depEntry = depIterator.next();
//If the key's values have no dependencies
if(depEntry.getValue().size()==0){
//System.out.println(depEntry.getKey());
listofAllDependency.add(depEntry.getKey());
dependencyTable.remove(depEntry);
depIterator.remove();
}
for(Dependency dep :depEntry.getValue()){
if(!dependencyTable.containsKey(dep)){
allValuesDependentsAreBuilt.add("true");
}else
{
allValuesDependentsAreBuilt.add("false");
}
}
if(!allValuesDependentsAreBuilt.contains("false")){
listofAllDependency.add(depEntry.getKey());
dependencyTable.remove(depEntry);
depIterator.remove();
}
}
}
It seems following line is culprit:
dependencyTable.remove(depEntry);
Don't do add/remove on datastructure while iterating (which will cause IllegalStateException
) .
Following should be enough:
depIterator.remove();
When looping over a data structure and adding or removing contents of that datastructure at the same time, you can run into problems. If you want to remove items from a list while iterating over the list I would recommend keeping track of what you want to remove and then removing it all after you are done looping. Looking at your code specifically I would keep this line
dependencyTable.remove(depEntry);
and take out the line of code that modifies the iterator
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.