嗨,我想了解 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
andlistIterator
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 ownremove
oradd
methods, the iterator will throw aConcurrentModificationException
. 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/