Iterators Foreach Loops Iterators An iterator abstracts the
Iterators & For-each Loops
Iterators • An iterator abstracts the process of scanning through a collection of elements. • The iterator ADT supports the following two methods: has. Next(): Test whethere are elements left in the iterator next(): Return the next element in the iterator
Iterator Example Person List Iterator person; friends; iterator; friends = new Array. List( ); . . . //Scan through the list iterator = friends. iterator( ); while ( iterator. has. Next( ) ) { person = (Person) iterator. next( ); System. out. println( person. get. Name( ) ); }
Generics Iterator Example Person List<Person> Iterator<Person> person; friends; iterator; friends = new Array. List<Person>( ); . . . //Scan through the list iterator = friends. iterator( ); while ( iterator. has. Next( ) ) { person = iterator. next( ); System. out. println( person. get. Name( ) ); }
For-Each • Shorthand for looping through elements returned by an iterator: for(Type name : expression) loop statement which is shorthand for Type name; for(Iterator<Type> it=expression. iterator( ); it. has. Next(); name = it. next() ) { loop_statements }
Generics Iterator Example Person List<Person> Iterator<Person> person; friends; iterator; friends = new Array. List<Person>( ); . . . //Scan through the list iterator = friends. iterator( ); while ( iterator. has. Next( ) ) { person = iterator. next( ); System. out. println( person. get. Name( ) ); }
Generics For-each Example Person List<Person> person; friends; friends = new Array. List<Person>( ); . . . //Scan through the list for ( person : friends ) { System. out. println( person. get. Name( ) ); }
- Slides: 7