-3

我正在尝试使用 try-catch 块处理 java ConcurrentModificationException 异常,但在编译代码时仍然遇到相同的错误。

import java.util.*;
public class failFast{
    public static void main(String[] args){
        Map<Integer,String> map = new HashMap<>();
        map.put(100,"Melani");
        map.put(101,"Harshika");
        map.put(102,"Nimna");

        Iterator itr = map.keySet().iterator();

        while(itr.hasNext()){
            System.out.println(itr.next());

            try{
                map.put(103,"Nirmani");
            }
            catch(Exception e){
                System.out.println("Exception is thrown "+e);
            }
            
        }

Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextNode(Unknown Source)
        at java.util.HashMap$KeyIterator.next(Unknown Source)
        at failFast.main(failFast.java:12)
4

1 回答 1

0

我现在不完全是您想要达到的目标(您的代码对我来说没有多大意义)。基本上你不能在迭代它时改变一个Map或另一个。Collection改变底层结构的唯一方法是使用实​​际Iterator,但这非常有限。捕获ConcurrentModificationException没有多大意义,因为对于您的代码,它总是会被抛出,所以捕获块将是您的正常代码流,这真的不好。

可能性1:复制keySet到另一个集合并迭代这个集合

import java.util.*;
public class FailFast{
    public static void main(String[] args){
        Map<Integer,String> map = new HashMap<>();
        map.put(100,"Melani");
        map.put(101,"Harshika");
        map.put(102,"Nimna");

        // Copy keySet to an other collection and iterate over this one
        Iterator itr = new ArrayList(map.keySet()).iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
            map.put(103,"Nirmani");            
        }

可能性2:收集所有更改并在循环后应用它们(这就是我要做的)

import java.util.*;
public class FailFast{
    public static void main(String[] args){
        Map<Integer,String> map = new HashMap<>();
        map.put(100,"Melani");
        map.put(101,"Harshika");
        map.put(102,"Nimna");

        Iterator itr = map.keySet().iterator();

        Map<Integer,String> changes = new HashMap<>();
        while(itr.hasNext()){
            System.out.println(itr.next());
            changes.put(103,"Nirmani");            
        }
        map.putAll(changes);
于 2021-05-26T06:15:36.217 回答