Iterators and the for-each Loop


Iterators and the for-each Loop

The for-each loop construct is built upon the Iterator construct. In order to be able to loop through a collection, the collection must be able to return an Iterator object when sent the iterator message. The for-each loop recognizes whether a collection is iterable or not by seeing if the collection implements the java.lang.Iterable interface.

In this upcoming example, you will modify the Session class to support iterating through its collection of students.

Code the following test in SessionTest:

 public void testIterate() {    enrollStudents(session);    List<Student> results = new ArrayList<Student>();    for (Student student: session)       results.add(student);    assertEquals(session.getAllStudents(), results); } private void enrollStudents(Session session) {    session.enroll(new Student("1"));    session.enroll(new Student("2"));    session.enroll(new Student("3")); } 

When you compile, you will receive an error, since Session does not yet support the ability to be iterated over.

 foreach not applicable to expression type        for (Student student: session)                              ^ 

You must change the Session class to implement the Iterable interface. Since you want the for-each loop to recognize that it is iterating over a collection containing only Student types, you must bind the Iterable interface to the Student type.

 abstract public class Session       implements Comparable<Session>, Iterable<Student> { // ... 

Now you only need to implement the iterator method in Session. Since Session merely encapsulates an ArrayList of students, there is no reason that the iterator method can't simply return the ArrayList's Iterator object.

 public Iterator<Student> iterator() {    return students.iterator(); } 



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net