問題描述
我正在閱讀有關 ConcurrentModificationException 以及如何避免它的信息.找到一篇文章.該文章中的第一個清單具有類似于以下的代碼,這顯然會導致異常:
I was reading about ConcurrentModificationException and how to avoid it. Found an article. The first listing in that article had code similar to the following, which would apparently cause the exception:
List<String> myList = new ArrayList<String>();
myList.add("January");
myList.add("February");
myList.add("March");
Iterator<String> it = myList.iterator();
while(it.hasNext())
{
String item = it.next();
if("February".equals(item))
{
myList.remove(item);
}
}
for (String item : myList)
{
System.out.println(item);
}
接著用各種建議解釋了如何解決問題.
Then it went on to explain how to solve the problem with various suggestions.
當我試圖重現它時,我沒有得到異常!為什么我沒有收到異常?
When I tried to reproduce it, I didn't get the exception! Why am I not getting the exception?
推薦答案
根據Java API docs Iterator.hasNext 不會拋出 ConcurrentModificationException
.
According to the Java API docs Iterator.hasNext does not throw a ConcurrentModificationException
.
檢查 "January"
和 "February"
后,您從列表中刪除一個元素.調用 it.hasNext()
不會拋出 ConcurrentModificationException
而是返回 false.因此,您的代碼干凈地退出.然而,最后一個字符串永遠不會被檢查.如果您將 "April"
添加到列表中,則會按預期獲得異常.
After checking "January"
and "February"
you remove one element from the list. Calling it.hasNext()
does not throw a ConcurrentModificationException
but returns false. Thus your code exits cleanly. The last String however is never checked. If you add "April"
to the list you get the Exception as expected.
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String args[]) {
List<String> myList = new ArrayList<String>();
myList.add("January");
myList.add("February");
myList.add("March");
myList.add("April");
Iterator<String> it = myList.iterator();
while(it.hasNext())
{
String item = it.next();
System.out.println("Checking: " + item);
if("February".equals(item))
{
myList.remove(item);
}
}
for (String item : myList)
{
System.out.println(item);
}
}
}
http://ideone.com/VKhHWN
這篇關于為什么這段代碼不會導致 ConcurrentModificationException?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!