为什么我会收到ConcurrentModificationException?

kpr*_*rog 0 java linked-list priority-queue

为什么我在代码中的指定位置获得ConcurrentModificationException?我无法弄清楚我做错了什么...该removeMin()方法用于定位列表中的min pq,删除它,并返回其值

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

}
Run Code Online (Sandbox Code Playgroud)

VGR*_*VGR 5

一旦获得迭代器的集合被修改,它就不应被视为可用.(对java.util.concurrent.*集合类放宽了此限制.)

您首先获取Iterator pq,然后进行修改pq.修改后pq,Iterator itPQ不再有效,因此当您尝试使用它时,会收到ConcurrentModificationException.

一种解决方案是Iterator<Integer> itPQ = pq.iterator();while循环之前向右移动.更好的方法是完全废除Iterator的显式使用:

for (Integer element : pq) {
Run Code Online (Sandbox Code Playgroud)

从技术上讲,for-each循环在内部使用Iterator,所以无论哪种方式,只要你不尝试pq在循环内修改,这个循环才有效.