Generic Classes and 'for each' Loops List zoo = new ArrayList (); // … add several Animals to the zoo for (Animal animal : zoo) // do something with animal // do something with animal
Iterators List zoo = new ArrayList (); // Another way to loop over a collection Iterator it; it = zoo.iterator(); Animal animal; while (it.hasNext()) {animal = (Animal) it.next(); // Cast // next() returns a ref to Object // do something with animal // do something with animal it.remove();// remove from the collection }
Generic Classes and Iterators List zoo = new ArrayList (); Animal animal; // … add several Animals to the zoo Iterator it = zoo.iterator(); while (it.hasNext()) {animal = it.next();// No cast needed! {animal = it.next();// No cast needed! // do something with animal } // Iterator must be used when removing items from a collection.