我在迭代优先级队列时遇到问题,导致出现 ConcurrentmodificationException。
迭代代码:
Queue<Patient> pq = new PriorityQueue<Patient>();
Iterator<Patient> it = pq.iterator();
while(iter.hasNext()){
Patient current = iter.next();
if(current.getName().equals(patientName)){
pq.remove(p);
}
}
有错误表明 iter.next() 会导致并发修改异常。 我可以知道如何解决这个问题吗?我已经在互联网上搜索过,但仍然找不到解决方案。
最佳答案
将您的代码更改为以下代码来解决它 -
Queue<Patient> pq = new PriorityQueue<Patient>();
Iterator<Patient> iter = pq.iterator();
while(iter.hasNext()){
Patient current = iter.next();
if(current.getName().equals(patientName)){
iter.remove();
}
}
解释 ConcurrentModificationException
会从迭代器的 next() 方法抛出,如果底层集合(在您的情况下是队列)中有任何结构更改,即添加了任何元素或者直接从队列中删除。它被称为快速失败迭代器
。
关于Java 优先级队列中的并发修改异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41958628/