Cả hai đều là con trỏ (cursor) để duyệt collection. Enumeration từ JDK 1.0 (legacy), Iterator từ JDK 1.2 (Collection Framework).
Bảng so sánh chi tiết
| STT | Tiêu chí | Iterator | Enumeration |
|---|---|---|---|
| 1 | Khả năng | Đọc và xóa element khi duyệt | Chỉ đọc (read-only) |
| 2 | Áp dụng cho | Tất cả class trong Collection Framework | Chỉ legacy class: Vector, Hashtable |
| 3 | Fail-Fast / Fail-Safe | Fail-fast: ném ConcurrentModificationException nếu collection bị sửa khi đang iterate |
Fail-safe: không ném exception (làm việc trên bản sao/snapshot) |
| 4 | Hạn chế | Chỉ duyệt tiến (forward) | Không thể xóa element |
| 5 | Method | hasNext(), next(), remove(), forEachRemaining() (Java 8) |
hasMoreElements(), nextElement() |
Ví dụ Enumeration (Legacy)
Vector<String> v = new Vector<>();
v.add("Apple"); v.add("Cat"); v.add("Dog");
Enumeration<String> e = v.elements();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
// Không thể xóa khi đang enumerate
Ví dụ Iterator (Modern)
List<String> list = new ArrayList<>();
list.add("Apple"); list.add("Cat"); list.add("Dog");
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if ("Cat".equals(s)) {
it.remove(); // An toàn xóa khi iterate
}
}
Lưu ý quan trọng
- Fail-fast của Iterator không đảm bảo (best-effort) - chỉ dùng để detect bug, không dùng cho logic kiểm soát luồng.
- Muốn xóa an toàn khi iterate trong multi-thread: dùng
CopyOnWriteArrayListhoặcConcurrentHashMap(iterator weakly consistent). ListIterator(sub-interface của Iterator) cho phép duyệt 2 chiều, add/set element.- Java 5+: Ưu tiên enhanced for-loop hoặc
forEachcho code sạch hơn.