RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 835695
Accepted
Санаев
Санаев
Asked:2020-05-31 08:16:51 +0000 UTC2020-05-31 08:16:51 +0000 UTC 2020-05-31 08:16:51 +0000 UTC

ConcurrentModificationException 和 Hashmap

  • 772

ConcurrentModificationExceptionHello在此行for (Transaction t : c.getTransactions())(第 64 行)上抛出 Exception 2 次迭代。我理解错误的本质——它发生在迭代器的元素在循环中被删除时。试图将 remove 更改为removeIF,但同样的错误。这是一个独特的问题,因为它发生在满足其解决方案的所有要求时。

private static void iteration() {
        Integer n = 1;
        Integer k = 1;
        Double maxProfit;
        Integer clusterInd;
        while (k > 0) {
            System.out.println("Итерация " + n);
            n++;
            k = 0;
            for (int i=0;i<clusters.size();i++) {
                Cluster c = clusters.get(i);
                for (Transaction t : c.getTransactions()) {//ошибку кидает здесь на 2 итерации
                    maxProfit = profit();
                    clusterInd = -1;
                    c.deleteTransaction(t);
                    int j = 0;
                    for (Cluster cl : clusters) {
                        if (j != i) {
                            cl.addTransaction(t);
                            Double p = profit();
                            if (p > maxProfit) {
                                maxProfit = p;
                                clusterInd = j;
                            }
                            cl.deleteTransaction(t);
                        }
                        j++;
                    }
                    if (clusterInd == -1){
                        clusters.get(i).addTransaction(t);
                    }else {
                        k++;
                        clusters.get(clusterInd).addTransaction(t);
                    }
                }
            }
        }
        System.out.println(k);
    }

删除事务的函数:

public void deleteTransaction(Transaction m) {
        if (this.count > 0) {
            String[] trans = m.getTrans();
            for (String s : trans) {
                this.square--;
                if (freq.containsKey(s)) {
                    if (freq.get(s) > 0) {
                        this.freq.put(s, freq.get(s) - 1);
                        if (this.freq.get(s) == 0) {
                            this.width--;
                            freq.entrySet().removeIf(entry -> entry.getKey().equals(s));
                        }
                    }
                }
            }
            this.count--;
            if (this.count > 0) {
                this.height = (double) this.square / this.width;
            } else {
                this.height = 0.0;
            }
            transactions.removeIf(m::equals);
        }
    }

日志:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:939)
    at java.base/java.util.ArrayList$Itr.next(ArrayList.java:893)
    at com.lab6.ClopeAlgorithm.iteration(ClopeAlgorithm.java:64)
    at com.lab6.ClopeAlgorithm.main(ClopeAlgorithm.java:96)
java
  • 4 4 个回答
  • 10 Views

4 个回答

  • Voted
  1. Sergey Gornostaev
    2020-05-31T13:37:30Z2020-05-31T13:37:30Z

    代替 foreach 循环,使用显式迭代器及其remove方法。

    • 1
  2. Санаев
    2020-05-31T14:02:34Z2020-05-31T14:02:34Z

    建议的解决方案:更改 for (Transaction t : c.getTransactions())为

    for (int i=0;i<clusters.size();i++) { 
     Cluster c = clusters.get(i); 
     List<Transaction> transactions = new ArrayList<>(c.getTransactions()); 
     for (Transaction t : transactions) { 
    ... 
    } 
    } 
    
    • 0
  3. Best Answer
    And
    2020-05-31T14:15:12Z2020-05-31T14:15:12Z

    让我们创建一个小地图:

    final HashMap<Object, Object> map = new HashMap<>();
    map.put("1", "1");
    map.put("2", "2");
    map.put("3", "3");
    

    以下表达式将引发错误:

    Java 8+:

    map.entrySet().stream().filter((i) -> ("3".equals(i.getKey()))).forEachOrdered((i) -> {
        map.remove(i.getKey());
    });
    

    爪哇 < 8:

    for (Entry<Object, Object> i : map.entrySet()) {
        if ("2".equals(i.getKey())) {
             map.remove(i.getKey());
        }
    }
    

    不会抛出错误的表达式:
    仅适用于 1 个删除,如果添加另一个if要删除,则会抛出错误NoSuchElementException

    final Iterator<Entry<Object, Object>> i = map.entrySet().iterator();
    while (i.hasNext()) {
        if ("2".equals(i.next().getKey())) {
           i.remove();
        }
    }
    

    如果我们想删除两个或更多元素,我们可以使用:

    while (i.hasNext()) {
        switch ((String) i.next().getKey()) {
            case"2":
            case"3":
                i.remove();
            break;                 
        }
    }
    

    要删除、添加、更改,最好使用switch:

    final Map<Object, Object> map = new ConcurrentHashMap<>();
    map.put("1", "1");
    map.put("2", "2");
    map.put("3", "3");
    map.put("4", "5");
    final Iterator<Entry<Object, Object>> i = map.entrySet().iterator();
    while (i.hasNext()) {
        switch ((String) i.next().getKey()) {
            case "3":
                i.remove();
                map.put("5", "5");
                final Iterator<Entry<Object, Object>> it = map.entrySet().iterator();
                while (it.hasNext()) {
                    if ("2".equals((String) it.next().getKey())) {
                        it.remove();
                        map.put("5", "5");
                        map.put("6", "6");
                        map.remove(map.get("1"));
    
                    }
                }
            break;
        }
    }
    System.out.println(map); // {4=5, 5=5, 6=6}
    

    但同样,这一切都有副作用。
    如果某些物体飞入存储,则在:

    while (i.hasNext()) {
        switch((String)i.next().getKey()) {
           //.....
        }
    }
    

    我们得到ConcurrentModificationException.
    在您的情况下,您可以使用 like mutex。

    synchronized(map) {
       //....
    }
    

    这样就可以不怕它飞了。

    • 0
  4. Bombaster
    2020-05-31T08:56:09Z2020-05-31T08:56:09Z

    Foreach 是一种处理集合元素的机制,而不是集合本身。使用 foreach 修改集合不再正确。而写拐杖和自行车来“扩大语言设计的可能性”根本就是个坏主意。这种方法将破坏将实现 A 替换为实现 B 的能力,而无需手鼓跳舞并重写在 foreach 中修改集合的所有代码。

    这是经典的迭代器方法之一:

    for (Iterator<Integer> it = set.iterator(); it.hasNext(); ) {
      if (it.next() % 2 == 0) {
        it.remove();
      }
    }
    



    取自这里:

    https://habr.com/post/325426/#comment_10149968

    • -3

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    是否可以在 C++ 中继承类 <---> 结构?

    • 2 个回答
  • Marko Smith

    这种神经网络架构适合文本分类吗?

    • 1 个回答
  • Marko Smith

    为什么分配的工作方式不同?

    • 3 个回答
  • Marko Smith

    控制台中的光标坐标

    • 1 个回答
  • Marko Smith

    如何在 C++ 中删除类的实例?

    • 4 个回答
  • Marko Smith

    点是否属于线段的问题

    • 2 个回答
  • Marko Smith

    json结构错误

    • 1 个回答
  • Marko Smith

    ServiceWorker 中的“获取”事件

    • 1 个回答
  • Marko Smith

    c ++控制台应用程序exe文件[重复]

    • 1 个回答
  • Marko Smith

    按多列从sql表中选择

    • 1 个回答
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Suvitruf - Andrei Apanasik 什么是空? 2020-08-21 01:48:09 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5