Midterm Review1.8 - Iterators An Iterator is an object that...

Info icon This preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
Last Updated: 1/7/10 10:14 AM CSE 2011 Prof. J. Elder - 36 - Iterators ± An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. ± You get an Iterator for a collection by calling its iterator method. ± Suppose collection is an instance of a Collection . Then to print out each element on a separate line: Iterator<E> it = collection .iterator(); while ( it .hasNext()) System.out.println( it .next());
Image of page 1

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

View Full Document Right Arrow Icon
Last Updated: 1/7/10 10:14 AM CSE 2011 Prof. J. Elder - 37 - The Enhanced For-Each Statement ± Suppose collection is an instance of a Collection . Then for ( Object o : collection ) System.out.println(o); prints each element of the collection on a separate line. ± This code is just shorthand: it compiles to use o.iterator().
Image of page 2