java - 为什么ListIterator.add不抛出ConcurrentModificationException但下面的list.add抛出异常?

标签 java data-structures

嗨,我想了解 ListIterator 上的添加操作是如何工作的。我不明白为什么第 7 行让我将项目添加到迭代器,而第 8 行抛出 ConcurrentModificationException。将项目添加到 ListIterator 与将项目添加到 List 有什么区别。两者都在努力实现同样的目标。

List<String> list = new ArrayList<String>();
list.add("hi");
list.add("whats up");
list.add("how are you");
list.add("bye");

ListIterator<String> i = list.listIterator();

while (i.hasNext()) {
    System.out.println(i.next());
    list.add("Sample"); // Line #7
    i.add("Test"); // Line #8
}
System.out.println(list);

最佳答案

List.add 将指定元素追加到此列表的末尾。

ListIterator.add 粗略地说“在当前位置之后”插入指定元素。更准确地说,该元素被插入到 next() 返回的元素(如果有)之前,以及 previous() 返回的元素(如果有)之后。另外,使用 ListIterator.add 添加元素不会产生 ConcurrentModificationException

您会收到 ConcurrentModificationException,因为您在迭代列表迭代器时调用 list.add。这是由于fail-fast特点:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

这正是正在发生的事情。您可以直接修改列表(而不是通过迭代器自己的方法)。

关于java - 为什么ListIterator.add不抛出ConcurrentModificationException但下面的list.add抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49720766/

相关文章:

Java:使用 getter 从数组列表中检索并打印项目

c - 反转链表

java - eclipse "scanner.ensureopen() line not available "

java - 修改单个玩家的消息

java - 开始在 Android 2.3 上编程

python - 如何在python中合并两个数据结构

java - Java 中的双端队列

java - 覆盖所有其他组件(Swing、Java)

java - 无法启动: error in configuration file(s) Can't find setting 'Scenario.nrofHostGroups' Java Result: -1

c# - 深层嵌套字典是反模式吗?