【问题标题】:Concurrent modification when next() has exhausted elementsnext() 已用尽元素时的并发修改
【发布时间】:2019-12-29 18:44:19
【问题描述】:

最近一直在阅读Iterators。假设我们要为给定的容器类构建一个 fail-fast 迭代器。在某个时间点,执行了以下代码;

Iterator<Object> it = myContainer.iterator();
while(it.hasNext())
    System.out.println(it.next());

然后,我们对myContainer 进行修改,例如使用称为remove(int index 的方法:

myContainer.remove(2);      // Assume at least 3 elements contained

如果it.next() 被称为现在,并且根据官方文档,我们应该抛出ConcurrentModificationExceptionNoSuchElementException 的实例吗?也许更重要的是,这是否可以从官方文档中推断出来?

【问题讨论】:

  • 请解释清楚,不清楚。你想在这里做什么。
  • 我正在尝试找出两个 Exceptions 中的哪一个 应该 由想要实现 fail-fast 的人抛出Iterator 给定容器的类,如堆栈、列表、优先级队列...

标签: java iterator concurrentmodification nosuchelementexception


【解决方案1】:

你应该抛出一个ConcurrentModificationExceptionNoSuchElementException 表示迭代器中没有更多元素。当您遇到并发修改时,它总是会否决 NoSuchElementException。至少 ArraylistLinkedList 是如何做到的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多