【问题标题】:ConcurrentModificationException with ArrayLists and HashMaps [duplicate]ConcurrentModificationException 与 ArrayLists 和 HashMaps [重复]
【发布时间】:2018-03-26 15:15:10
【问题描述】:

我一直在开发的数据库函数依赖算法遇到问题。我正在尝试计算给定格子的当前级别和列头列表(不是真正相关的)的函数依赖关系。

我正在尝试遍历字符串标题列表,以及遍历每个字符串的字符。以此推理,然后我使用这些值从映射中的List<String> 值中删除一个字符串。 Map 的结构为<String, List<String>>,我想简单地从HashMap 的List<String> 值中删除一个值。 colHeadsList<String>

当我开始循环遍历列表时出现 ConcurrentModificationException:

for (String x: level) {
        for (char a : x.toCharArray()) {
            if (cPlusHash.get(x).contains(Character.toString(a))) {
                if (checkFD(Arrays.asList(x.replace("a", "")), Arrays.asList(Character.toString(a)))){
                    fds.add(x.replace("a", "") +", "+ a );  
                    cPlusHash.remove(x, Character.toString(a));



                    for (char j : x.toCharArray()) {
                        if (colHeads.contains(Character.toString(j))) {
                            colHeads.remove(Character.toString(j));
                        }
                    }
                    for (String b : colHeads) {
                        if (cPlusHash.get(x).contains(b)) {
                            cPlusHash.remove(x, b);
                        }
                    }
                }
            }
        }

我在这个 sn-p 代码的第一行得到了错误。我很困惑,因为我实际上并没有尝试修改我正在迭代的 List 的值。

【问题讨论】:

    标签: java exception arraylist hashmap concurrentmodification


    【解决方案1】:

    在大多数情况下,您无法在循环访问列表或地图时对其进行修改。解决方法是获取一个Iterator,它提供了remove()方法。这使迭代器能够了解更改并且不会“丢失它的位置”。

    【讨论】:

      【解决方案2】:

      您在阅读时尝试修改地图cPlusHash<String, List<String>>,这是不允许的并导致ConcurrentModificationException

      https://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html

      你的情况是单线程情况:

      如果单个线程发出一系列违反对象约定的方法调用,则该对象可能会抛出此异常。例如,如果线程在使用快速失败迭代器迭代集合时直接修改了集合,则迭代器将抛出此异常。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-06
        • 2010-12-07
        • 2014-09-01
        • 1970-01-01
        • 2016-11-03
        • 2013-09-26
        • 1970-01-01
        • 2021-07-01
        相关资源
        最近更新 更多