Iterators - PowerPoint PPT Presentation

About This Presentation
Title:

Iterators

Description:

System.out.printf('List item is: %s', nextStr); Iterator Example with Generics ... Has an add() method. Has a set() method to replace elements ... – PowerPoint PPT presentation

Number of Views:152
Avg rating:3.0/5.0
Slides: 7
Provided by: danf5
Learn more at: https://cs.gmu.edu
Category:
Tags: iterators | method

less

Transcript and Presenter's Notes

Title: Iterators


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 interface java.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
  • ArrayListltStringgt aList new ArrayListltStringgt()
  • populateListWithStrings(aList)
  • IteratorltStringgt 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 dont?
  • 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()
Write a Comment
User Comments (0)
About PowerShow.com