Iterator<E> là interface duyệt collection mà không cần biết cấu trúc bên trong (mảng, linked list, tree...).
java
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.isEmpty()) it.remove(); // xoá AN TOÀN trong khi duyệt
}Lý do quan trọng nhất — xoá an toàn: đoạn sau throw ConcurrentModificationException:
java
for (String s : list) {
if (s.isEmpty()) list.remove(s); // ❌ CME
}Phải dùng iterator.remove() hoặc list.removeIf(String::isEmpty).
Lưu ý:
- Enhanced for-loop thực ra là syntactic sugar của Iterator.
- ListIterator: chỉ cho List, duyệt 2 chiều + set/add tại chỗ.
- forEach(Consumer) (Java 8+): internal iteration — không remove() trong lúc duyệt, dùng removeIf.
Quy tắc: ưu tiên enhanced for hoặc Stream; dùng iterator tường minh chỉ khi cần remove().