在Java中,對(duì)于容器的遍歷有for循環(huán)和爹代器兩種方法,其中,for循環(huán)有包括了傳統(tǒng)的for循環(huán)和for each方法。迭代器主要用Uterator(另外還有ListIterator ,雙向迭代器;Enumeration,相當(dāng)于Iterator?,F(xiàn)已取代)
具體使用方法(以包含Integer元素的 List為例):
傳統(tǒng)for:
? ? ?for(int i=0;i<list.size();i++){
? ? ? ? ? ? ? ? ...
? ? ? ? }
for each:
? ? for(Integer item:list){
? ? ? ? ...
? ? }
迭代器:
? ? ?Iterator item = list.iterator();
? ? ? ? while(? item.hasNext()){
? ? ? ? ? ? Integer?dat = intem.next();
? ? ? ? ? ? ...
? ? ? ? }
在以上三種迭代方法中,如果要一邊遍歷,一邊刪除元素,則必須用迭代器方式。若果使用for each刪除,則會(huì)觸發(fā)`ConcurrentModificationException`錯(cuò)誤:
? ? for (Object e : list) {
? ? ? ? ? ? ? ? System.out.println(e);
? ? ? ? ? ? ? ? if("b".equals(e)){
? ? ? ? ? ? ? ? ? ? list.remove(e);//操作集合的刪除方法
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? 運(yùn)行結(jié)果:
? ? a
? ? b
? ? Exception in thread "main" java.util.ConcurrentModificationException
? ? 修改
? ? Iterator it=list.iterator();
? ? ? ? ? ? while(it.hasNext()){
? ? ? ? ? ? ? ? Object e=it.next();
? ? ? ? ? ? ? ? if("b".equals(e)){
? ? ? ? ? ? ? ? ? ? it.remove();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? System.out.println(list);
**不能使用集合類的remove方法,而是要使用Iterator的remove方法**