在我的代碼:ConcurrentModificationException的在foreach循環
Collection<String> c = new ArrayList<>();
Iterator<String> it = c.iterator();
c.add("Hello");
System.out.println(it.next());
異常occures,因爲迭代器創建後,我的收藏改變。
但是,我們在此代碼:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
for (Integer integer : list) { // Exception is here
if (integer.equals(2)) {
list.remove(integer);
}
}
爲什麼出現異常?
在第二個代碼中,我在for-each循環之前在我的集合中進行了更改。
你什麼事remove()不,如果不修改集合刪除元素? –
for-each使用迭代器。 – kosa
這個問題似乎是無關緊要的,因爲它沒有顯示任何先前的研究 – njzk2