| 7 | |
| 8 | public class SimpleIteration { |
| 9 | public static void main(String[] args) { |
| 10 | List<Pet> pets = new PetCreator().list(12); |
| 11 | Iterator<Pet> it = pets.iterator(); |
| 12 | while(it.hasNext()) { |
| 13 | Pet p = it.next(); |
| 14 | System.out.print(p.id() + ":" + p + " "); |
| 15 | } |
| 16 | System.out.println(); |
| 17 | // A simpler approach, when possible: |
| 18 | for(Pet p : pets) |
| 19 | System.out.print(p.id() + ":" + p + " "); |
| 20 | System.out.println(); |
| 21 | // An Iterator can also remove elements: |
| 22 | it = pets.iterator(); |
| 23 | for(int i = 0; i < 6; i++) { |
| 24 | it.next(); |
| 25 | it.remove(); |
| 26 | } |
| 27 | System.out.println(pets); |
| 28 | } |
| 29 | } |
| 30 | /* Output: |
| 31 | 0:Rat 1:Manx 2:Cymric 3:Mutt 4:Pug 5:Cymric 6:Pug |