0

The runtime indicates the exception occurs when giving temp = keysit.next(). I thought this had been taken care of when I redefined keysit = keys.iterator() for the 2nd time, but maybe I'm missing the point. Any suggestions?

Map<Integer, Set<String>> lhm = new LinkedHashMap<Integer, Set<String>>();

public void sortMap() {
    Set<Integer> keys = hm.keySet();
    Iterator<Integer> keysit;
    int iterations = keys.size();
    int smallest;
    int temp;
    for(int i=0; i<iterations; i++) {
        keysit = keys.iterator();
        smallest = keysit.next();
        keysit = keys.iterator();  
        while(keysit.hasNext()) {
            temp = keysit.next();  
            if(temp<smallest) 
                smallest = temp;
            lhm.put(smallest, lhm.get(smallest));
            keys.remove(smallest);
        }
    }
    System.out.println(lhm);
}
Xaba
  • 3
  • 5

2 Answers2

-1

Use a Concurrenthashmap instead of a hashmap or map bcoz hashmap is not threadsafe

Zuko
  • 2,764
  • 30
  • 30
  • Thread safety is not the issue here, it will throw a ConcurrentModificationException in a single-threaded application just as well. The problem is you're removing elements from the set while iterating over it. You should use the iterator's `remove()` method instead, if it supports it. – Jan Van den bosch Dec 13 '16 at 06:50
-1

The point is iterator maintains an integer flag named - modCount which keep track of modifications during iteration.

In following line of code

keys.remove(smallest);

you are actually removing element from the set which changes this modcount. So next time when next() is called to get the next element, it checks whether modcount value has been changed or not. If yes then throw concurrent modification exception.

So all in all the modification is dependent on the modcount flag and doesn't depend on how many times you redefine keys.iterator().

One good option is to use ConcurrentHashMap as suggested by @Olu

Vaibhav Jain
  • 1,939
  • 26
  • 36