2

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
3
  • 1
    Delete after the loop. Store the values you want to delete in a Collection and once you have exited the loop, delete. Commented Sep 23, 2013 at 14:59
  • btw, I don't like the if(nod.getLabel() == part. Prefer equals() if possible. Commented Sep 23, 2013 at 15:05
  • Sadly, this is a prime example of a misleading exception name. ConcurrentModificationException does 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. Commented Sep 23, 2013 at 15:07

1 Answer 1

4

The problem is that you are removing an item using an iterator (good practice) but the other iterator is not aware of that. Hence, the call to it.next() fails.

You should try to use only one iterator or remove items after looping.

EDIT : After analyzing your question, it seems that your need is to create a Collection of unique items. This makes me think that you would like to use a Set with a well-formed Comparator. In this way, adding all your items to your Set will automatically remove duplicates.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.