Enumeration 將「穿越序列」操作與「序列底層結構」完全解耦。客戶代碼只需依賴 Enumeration 介面,無需知道底層是 Vector、Hashtable 還是其他集合。
class PrintData {
static void print(Enumeration e) {
while (e.hasMoreElements())
System.out.println(e.nextElement().toString());
}
}
// 使用端
Vector v = new Vector(); v.addElement(new Mouse(i));
Hashtable h = new Hashtable(); h.put(new Integer(i), new Hamster(i));
PrintData.print(v.elements());
PrintData.print(h.elements());
PrintData.print() 完全不知底層集合型別,只調用 toString() (Object 方法)。
若需調用特定方法 (如 Shape.draw()),必須從 nextElement() 返回的 Object 下溯造型:
Shape s = (Shape) e.nextElement(); s.draw();
這是 Java 1.2 泛型引入前的通用模式,也是理解現代 Iterator 泛型設計的基礎。