Presentation is loading. Please wait.

Presentation is loading. Please wait.

Generic Classes and 'for each' Loops List zoo = new ArrayList (); // … add several Animals to the zoo for (Animal animal : zoo) // do something with animal.

Similar presentations


Presentation on theme: "Generic Classes and 'for each' Loops List zoo = new ArrayList (); // … add several Animals to the zoo for (Animal animal : zoo) // do something with animal."— Presentation transcript:

1 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

2 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 }

3 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.


Download ppt "Generic Classes and 'for each' Loops List zoo = new ArrayList (); // … add several Animals to the zoo for (Animal animal : zoo) // do something with animal."

Similar presentations


Ads by Google