27iterator - Robert Sedgewick and Kevin Wayne • Copyright...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Robert Sedgewick and Kevin Wayne • Copyright © 2006 • http://www.Princeton.EDU/~cos226 2.7 Lists and Iterators 2 Sequences and Urns Sequence. Ordered collection of items. Key operations. Insert an item, iterate over the items. Design challenge. Support iteration by client, without revealing the internal representation of the collection. was the best of It times next Robert Sedgewick and Kevin Wayne • Copyright © 2006 • http://www.Princeton.EDU/~cos226 Iteration in Java 4 Iterator Interface API for java.util.Iterator . ! hasNext() Are there more items in the list? ! next() Return the next item in the list. ! remove() Delete the last item returned by next() . public interface Iterator < Item > { boolean hasNext (); Item next (); void remove (); // optional } was the best of It times next 5 public static void main ( String [] args ) { Sequence < String > list = new Sequence < String >(); list . add ( "This" ); list . add ( "is" ); list . add ( "a" ); list . add ( "test." ); Iterator < String > i = list . iterator (); while ( i . hasNext ()) { String s = i . next (); System . out . println ( s ); } } Iterator Client API for java.util.Iterator . ! hasNext() Are there more items in the list? ! next() Return the next item in the list. ! remove() Delete the last item returned by next() . 6 Iterable Interface API for java.lang.Iterable . ! iterator() Return an iterator. Ex. Sequence , java.util.ArrayList , HashSet . public interface Iterable < Item > { Iterator < Item > iterator (); } 7 Enhanced For Loop Enhanced for loop. Syntactic sugar for iterating over a collection. Remark. Can also use enhanced for loop with arrays. public static void main ( String [] args ) { Sequence < String > list = new Sequence < String >(); list.add("This"); list.add("is"); list.add("a"); list.add("test."); for ( String s : list ) System . out . println ( s ); } implements Iterable !...
View Full Document

This note was uploaded on 03/14/2011 for the course CS 102 taught by Professor David during the Spring '08 term at Bilkent University.

Page1 / 6

27iterator - Robert Sedgewick and Kevin Wayne • Copyright...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online