6
Iterators Dan Fleck

Iterators

Embed Size (px)

DESCRIPTION

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(); - PowerPoint PPT Presentation

Citation preview

Page 1: Iterators

Iterators

Dan Fleck

Page 2: Iterators

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

Page 3: Iterators

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);

}

Page 4: Iterators

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);

}

Page 5: Iterators

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…)?

Page 6: Iterators

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()