使用Set

时间:2016-12-13 05:46:05

标签: java exception set concurrentmodification

运行时指示在给出temp = keysit.next()时发生异常。当我第二次重新定义keysit = keys.iterator()时,我认为这已经得到了解决,但也许我错过了这一点。有什么建议吗?

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);
}

2 个答案:

答案 0 :(得分:-1)

使用Concurrenthashmap而不是hashmap或map bcoz hashmap不是线程安全的

答案 1 :(得分:-1)

重点是迭代器维护一个名为-modCount的整数标志,它在迭代期间跟踪修改。

以下代码行

keys.remove(smallest);

您实际上是从更改此modcount的集合中删除元素。因此,下次调用next()来获取下一个元素时,它会检查modcount值是否已更改。如果是,则抛出并发修改异常。

所有修改都取决于modcount标志,并不取决于你重新定义keys.iterator()的次数。

一个好的选择是使用@Olu

建议的ConcurrentHashMap