2015-06-29 60 views
-2

下面給出的代碼不會拋出ConcurrentModificationException.But,如果我在LinkedList中添加了2個元素,它會拋出異常。爲什麼?LinkedList上的ConcurrentModificationException

List<String> list = new LinkedList<String>(); 
list.add("A"); 
list.add("B"); 

for (String s : list) { 
    if (s.equals("B")) { 
     list.remove(s); 
    } 
} 
+0

請訪問http:// stackoverflow.com/a/223929/4290096 –

+0

可能的重複[遍歷列表,避免ConcurrentModificationException在循環中刪除時](http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception - 什麼時候刪除) – nogard

+0

我想問哪個問題更多次,這個或者字符串比較.. – drgPP

回答

2

使用增強型for循環在迭代整個集合時無法刪除項目。你想要做的,而不是這是什麼:

Iterator<String> iterator = list.iterator(); 
while (iterator.hasNext()) { 
    String s = iterator.next(); 
    if (s.equals("B")) { 
    iterator.remove(); 
    } 
} 
+0

我知道迭代器很好f或這樣的操作,但我很好奇,知道爲什麼只有最後和第二個最後的元素從鏈接列表中刪除而不拋出ConcurrentModificationException? – Bibhudutta

1

你不能從中刪除列表中的條目在for循環中,你必須使用一個迭代器,這樣的:

List<String> list = new LinkedList<String>(); 
list.add("A"); 
list.add("B"); 
Iterator<String> iterator = list.iterator(); 
while(iterator.hasNext()) { 
    String entry = iterator.next(); 
    if(entry.equals("B") { 
    iterator.remove(); 
    } 
} 
+1

嗯,這是不可思議的。 :P –

+0

@RedRoboHood你是什麼意思? =) –

+0

看看我的帖子,現在在你的,現在回到我的。 Heheheh ... –

相關問題