更新时间:2023-12-04 20:27:22
ArrayList 返回的迭代器是 fail-fast
本质上.
Iterators returned by ArrayList is fail-fast
in nature.
该类的迭代器和listIterator
方法返回的迭代器为fail-fas
t:如果在迭代器创建后的任何时间对列表进行结构修改,在任何除非通过迭代器自己的remove 或add 方法,否则迭代器将抛出一个ConcurrentModificationException
.因此,面对并发修改,迭代器会快速而干净地失败,而不是冒着在未来不确定的时间出现任意、非确定性行为的风险.
The iterators returned by this class's iterator and
listIterator
methods arefail-fas
t: 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 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.
对于集合的增强 for 循环 Iterator
被使用,因此您不能在迭代时调用 remove 方法.
For enhanced for loop for collections Iterator
gets used so you can not call remove method while you are iterating.
所以你的循环和下面一样
So your loop is same as below
for (Iterator<Entry> i = c.iterator(); i.hasNext(); ){
您可以调用 iterator.remove();
并基于迭代器显式而不是隐式地更改循环.
You can call iterator.remove();
and change loop based on iterator explicitly rather than implicitly.
String inputWord = "john";
ArrayList<String> wordlist = new ArrayList<String>();
wordlist.add("rambo");
wordlist.add("john");
for (ListIterator<String> iterator = wordlist.listIterator(); iterator
.hasNext();) {
String z = iterator.next();
if (z.equals(inputWord)) {
iterator.remove();
}
}
System.out.println(wordlist.size());