1 / 6

Iterators

Iterators. Dan Fleck. Iterators. Iterator Object that can access a collection of objects one object at a time Traverses the collection of objects JCF defines generic interface java.util.Iterator And a subinterface ListIterator. Iterator Example. ArrayList aList = new ArrayList();

Télécharger la présentation

Iterators

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Iterators Dan Fleck

  2. Iterators • Iterator • Object that can access a collection of objects one object at a time • Traverses the collection of objects • JCF defines generic interfacejava.util.Iterator • And a subinterface ListIterator

  3. Iterator Example ArrayList aList = new ArrayList(); populateListWithStrings(aList); Iterator itr = aList.iterator(); while (itr.hasNext()) { String nextStr = (String)itr.next(); System.out.printf(“List item is: %s”, nextStr); }

  4. Iterator Example with Generics ArrayList<String> aList = new ArrayList<String>(); populateListWithStrings(aList); Iterator<String> itr = aList.iterator(); while (itr.hasNext()) { String nextStr = itr.next(); System.out.printf(“List item is: %s”, nextStr); }

  5. Iterator methods • See Javadoc for Iterator • Do all Iterators implement the remove operation? What happens if they don’t? • What is another way to iterate through a Collection (ArrayList, Vector, Set, HashSet, LinkedList, etc…)?

  6. ListIterator Extends iterator to allow • reverse iteration of a List • “hasPrevious()”, “previous” methods • Has an add() method • Has a set() method to replace elements • Lets you get the index of the element • Int nextIndex(), int previousIndex()

More Related