//: CatsAndDogs2.java // Simple collection with Enumeration import java.util.*;
class Cat2 { PRivate int catNumber; Cat2(int i) { catNumber = i; } void print() { System.out.println("Cat number " +catNumber); } }
class Dog2 { private int dogNumber; Dog2(int i) { dogNumber = i; } void print() { System.out.println("Dog number " +dogNumber); } }
public class CatsAndDogs2 { public static void main(String[] args) { Vector cats = new Vector(); for(int i = 0; i < 7; i++) cats.addElement(new Cat2(i)); // Not a problem to add a dog to cats: cats.addElement(new Dog2(7)); Enumeration e = cats.elements(); while(e.hasMoreElements()) ((Cat2)e.nextElement()).print(); // Dog is detected only at run-time } } ///:~
我们看到唯一的改变就是最后几行。不再是:
for(int i = 0; i < cats.size(); i++) ((Cat)cats.elementAt(i)).print();
public class HamsterMaze { public static void main(String[] args) { Vector v = new Vector(); for(int i = 0; i < 3; i++) v.addElement(new Hamster(i)); Printer.printAll(v.elements()); } } ///:~