I am trying to iterate through a HashMap using 2 iterators. Firstly for every key(Integer) in the hash I compute "similar" numbers(it really doesn't matter what similar numbers are in this particular case) and then I have to delete the keys which are similar to the current key by making them values of the current key. I keep receiving this exception
Exception in thread "main" java.util.ConcurrentModificationException. What could be the cause? Do I have to use a ConcurrentHashMap?
This is the code I am compiling:
Set<Node> keySet = hash.keySet();
Iterator<Node> it = keySet.iterator();
while(it.hasNext()){
Node key = it.next();
ArrayList<Integer> similar = getAppropriateNum(key.getLabel(), 2);
for(int j = 0; j < similar.size(); j++){
Iterator<Node> it2 = keySet.iterator();
while(it2.hasNext()){
Node nod = it2.next();
if(nod.getLabel() == similar.get(j) && !nod.equals(key)){
it2.remove();
hash.put(key, nod);
}//end if
}//end while
}//end for
}//end while
if(nod.getLabel() ==part. Preferequals()if possible.ConcurrentModificationExceptiondoes not refer necessarily to a problem involving concurrency (i.e. multiple threads) and generally means that an iterator has come to have a stale view of the contents of a data structure. Whether this happened because a different thread modified the collection or the same one is irrelevant here.