* 普通for循環,可以刪除,但是索引要 “--”
* 迭代器,可以刪除,但是必須使用迭代器自身的remove方法,否則會出現並發修改異常
* 增強for循環不能刪除
增強for
* 簡化數組和Collection集合的遍歷
* B:格式:
for(元素數據類型 變量 : 數組或者Collection集合) {
使用變量即可,該變量就是元素
}
* C:案例演示
* 數組,集合存儲元素用增強for遍歷
* D:好處
* 簡化遍歷
增強for循環底層依賴的是迭代器(Iterator)
==================================================================
普通for循環:
注意:如果相鄰兩個元素為b;刪除第一個b后,后面的元素全部前移,后邊的那個B移到原來B的位置,而此時i已指向下一個元素
=============================================
迭代器刪除指定元素
Iterator<String> it = list.iterator();
while(it.hasNext()) {
if("b".equals(it.next())) {
//list.remove("b"); //不能用集合的刪除方法,因為迭代過程中如果集合修改會出現並發修改異常
it.remove();
}
}
for(Iterator<String> it2 = list.iterator(); it2.hasNext();) {
if("b".equals(it2.next())) {
//list.remove("b"); //不能用集合的刪除方法,因為迭代過程中如果集合修改會出現並發修改異常
it2.remove();
}
}
=================================================================
增強for循環,增強for循環不能刪除,只能遍歷
for (String string : list) {
if("b".equals(string)) {
list.remove("b");
}
}
System.out.println(list);
}