【发布时间】:2017-06-07 10:22:30
【问题描述】:
我有 Java 基础知识,目前正在编写基于 Java 的代码。
编辑:代码不是我写的
我正在遍历 Event 对象的排序树形图,并在尝试获取下一个元素时遇到此异常:
java.util.ConcurrentModificationException
at java.util.TreeMap$PrivateEntryIterator.nextEntry(Unknown Source)
at java.util.TreeMap$KeyIterator.next(Unknown Source)
我认为这应该是由于迭代器比较器合并了多个具有相同值的条目(参考这个question,但我不知道如何找到比较器中使用的键。对象Event 有很多参数(如id、时间等)但不确定哪个用于迭代器。
这里是相关代码部分(第二个SimEvent first = fit.next();中的异常):
if (future.size() > 0) {
List<SimEvent> toRemove = new ArrayList<SimEvent>();
Iterator<SimEvent> fit = future.iterator();
queue_empty = false;
SimEvent first = fit.next();
processEvent(first);
future.remove(first);
fit = future.iterator();
// Check if next events are at same time...
boolean trymore = fit.hasNext();
while (trymore) {
SimEvent next = fit.next();
if (next.eventTime() == first.eventTime()) {
processEvent(next);
toRemove.add(next);
trymore = fit.hasNext();
} else {
trymore = false;
}
}
future.removeAll(toRemove);
} else {...}
编辑:future类的大厅代码:
public class FutureQueue {
/** The sorted set. */
private final SortedSet<SimEvent> sortedSet = new TreeSet<SimEvent>();
/** The serial. */
private long serial = 0;
/**
* Add a new event to the queue. Adding a new event to the queue preserves the temporal order of
* the events in the queue.
*
* @param newEvent The event to be put in the queue.
*/
public void addEvent(SimEvent newEvent) {
newEvent.setSerial(serial++);
sortedSet.add(newEvent);
}
/**
* Add a new event to the head of the queue.
*
* @param newEvent The event to be put in the queue.
*/
public void addEventFirst(SimEvent newEvent) {
newEvent.setSerial(0);
sortedSet.add(newEvent);
}
/**
* Returns an iterator to the queue.
*
* @return the iterator
*/
public Iterator<SimEvent> iterator() {
return sortedSet.iterator();
}
/**
* Returns the size of this event queue.
*
* @return the size
*/
public int size() {
return sortedSet.size();
}
/**
* Removes the event from the queue.
*
* @param event the event
* @return true, if successful
*/
public boolean remove(SimEvent event) {
return sortedSet.remove(event);
}
/**
* Removes all the events from the queue.
*
* @param events the events
* @return true, if successful
*/
public boolean removeAll(Collection<SimEvent> events) {
return sortedSet.removeAll(events);
}
public void clear() {
sortedSet.clear();
}
}
关于如何继续调试此问题的任何建议?
【问题讨论】:
-
能否分享
future类的代码? -
为什么你有时使用 fit.next() 而不检查 fit.hasNext()?
-
@VasiliyVlasov:在问题编辑中完成
-
user7294900:我以这种方式获得此代码。在我得到异常之前,我已经检查了迭代器仍然有下一个元素。
-
不清楚您是否得到 java.util.ConcurrentModificationException(在问题中)或 java.util.NoSuchElementException(在标题中)。
标签: java iterator treemap sortedset