为什么会收到ConcurrentModificationException?

编程入门 行业动态 更新时间:2024-10-26 12:31:33
本文介绍了为什么会收到ConcurrentModificationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么在代码的指定位置会收到ConcurrentModificationException?我无法弄清楚自己在做什么错... removeMin()方法正用于在列表pq中定位最小值,将其删除并返回其值

Why do I get a ConcurrentModificationException at the specified location in my code? I cannot figure out what I am doing wrong... The removeMin() method is being used to locate the min in the list pq, remove it, and return its value

import java.util.Iterator; import java.util.LinkedList; public class test1 { static LinkedList<Integer> list = new LinkedList<Integer>(); public static void main(String[] args) { list.add(10); list.add(4); list.add(12); list.add(3); list.add(7); System.out.println(removeMin()); } public static Integer removeMin() { LinkedList<Integer> pq = new LinkedList<Integer>(); Iterator<Integer> itPQ = pq.iterator(); // Put contents of list into pq for (int i = 0; i < list.size(); i++) { pq.add(list.removeFirst()); } int min = Integer.MAX_VALUE; int pos = 0; int remPos = 0; while (itPQ.hasNext()) { Integer element = itPQ.next(); // I get ConcurrentModificationException here if (element < min) { min = element; remPos = pos; } pos++; } pq.remove(remPos); return remPos; } }

推荐答案

修改了从其获得的Collection后,不应认为Iterator可用. (对于java.util.concurrent.*集合类,放宽了此限制.)

An Iterator should not be considered usable once the Collection from which it was obtained is modified. (This restriction is relaxed for java.util.concurrent.* collection classes.)

您首先要获得pq的迭代器,然后修改pq.修改pq后,迭代器itPQ不再有效,因此当您尝试使用它时,会收到ConcurrentModificationException.

You are first obtaining an Iterator for pq, then modifying pq. Once you modify pq, the Iterator itPQ is no longer valid, so when you try to use it, you get a ConcurrentModificationException.

一种解决方案是将Iterator<Integer> itPQ = pq.iterator();移到while循环之前.更好的方法是完全不使用Iterator:

One solution is to move Iterator<Integer> itPQ = pq.iterator(); to right before the while loop. A better approach is to do away with the explicit use of Iterator altogether:

for (Integer element : pq) {

从技术上讲,for-each循环在内部使用Iterator,因此,无论哪种方式,该循环仅在您不尝试在循环内修改pq时才有效.

Technically, the for-each loop uses an Iterator internally, so either way, this loop would only be valid as long as you don’t try to modify pq inside the loop.

更多推荐

为什么会收到ConcurrentModificationException?

本文发布于:2023-06-07 22:08:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568651.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ConcurrentModificationException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!