如何邊遍歷邊移除Collection中的元素
邊遍歷邊修改Collection的唯一正確方式是使用Iterator.remove()方法,如下:
Iterator<Integer> it = list.iterator();
while(it.hasNext()){
// do something
it.remove();
}
一種最常見的錯誤代碼如下:
for(Integer i : list){
list.remove(i)
}
運行以上錯誤代碼會報ConcurrentModificationException異常。這是因為當使用foreach(for(Integer i : list))語句時,會自動生成一個iterator來遍歷該list,但同時該list正在被Iterator.remove()修改。在Java中,一般不允許一個線程在遍歷collection時另一個線程在修改它。