Iterators.

Slides:



Advertisements
Similar presentations
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Advertisements

Chapter 7 Iterators Modified. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using.
Computer Science 209 Software Development Iterators.
COMP 121 Week 11: Linked Lists. Objectives Understand how single-, double-, and circular-linked list data structures are implemented Understand the LinkedList.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Iterators Chapter 7. Chapter Contents What is an Iterator? A Basic Iterator Visits every item in a collection Knows if it has visited all items Doesn’t.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
Topic 3 The Stack ADT.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
Computer Science 209 The Factory Pattern. Collections and Iterators List list1 = new ArrayList (); List list2 = new LinkedList (); Set set1 = new HashSet.
CS2852 Week 3, Class 2 Today Stacks Queues SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
CS 367 Introduction to Data Structures Lecture 5.
Computer Science 209 Software Development Inheritance and Composition.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
Iteration Abstraction SWE Software Construction Fall 2009.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
Iterators. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using iterators to solve.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
Linked Structures - Stacks. Linked Structures An alternative to array-based implementations are linked structures A linked structure uses object references.
Stack: a Linked Implementation
Concepts of Programming Languages
The List ADT.
EECE 310: Software Engineering
The List ADT Reading: Textbook Sections 3.1 – 3.5
Storage Strategies: Dynamic Linking
ADT’s, Collections/Generics and Iterators
Chapter 12: Data Structures
CSE 373: Data Structures and Algorithms
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Chapter 16 Iterators.
Top Ten Words that Almost Rhyme with “Peas”
Iteration Abstraction
Chapter 7 Iterators.
Java Software Structures: John Lewis & Joseph Chase
Linked Lists.
THURSDAY, OCTOBER 17 IN LAB
Introduction to Collections
"First things first, but not necessarily in that order " -Dr. Who
Chapter 13 Collections.
ArraySet Methods and ArrayIterator
The List ADT Reading: Textbook Sections 3.1 – 3.5
Java Collections Framework
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Java Software Structures: John Lewis & Joseph Chase
Programming II (CS300) Chapter 07: Linked Lists and Iterators
Dynamic Data Structures and Generics
Iteration Abstraction
Example: LinkedSet<T>
Interator and Iterable
Introduction to Collections
Chapter 4 Queues.
List Implementation via Arrays
Software Design Lecture : 39.
TCSS 143, Autumn 2004 Lecture Notes
CSE 143 Lecture 21 Advanced List Implementation
Introduction to Java Collection
CHAPTER 3: Collections—Stacks
Presentation transcript:

Iterators

Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over or stepping through or visiting every item in the data structure or collection Example with a data structure (array): for (int i = 0; i < arr.length(); i++) /* do something to arr[i] */ This is straighforward because we know exactly how an array works!

Motivation What if we want to traverse a collection of objects? Like a list Its underlying implementation may not be known to us Java provides a common scheme for stepping through all elements in any collection, called an iterator

What is an Iterator? An iterator is a mechanism used to step through the elements of a collection one by one Each element is “delivered ” exactly once Example Iterate through an ordered list and print each element in turn 5 9 23 34 2-4

Iterator Interface The Java API has a generic interface called Iterator<T> that specifies what methods are required of an iterator public boolean hasNext( ); returns true if there are more elements in the iteration public T next( ); returns the next element in the iteration public void remove( ); removes the last element returned by the iterator (optional operation) It is in the java.util package of the Java API 2-5

Array Iterator If we had a collection with an array implementation, we would need an array implementation of the Iterator interface See ArrayIterator.java: Its attributes Its constructor The code for the methods hasNext and next In what order does it deliver the items? Note: ArrayIterator.java can be used by an array implementation of any collection!

// Represents an iterator over the elements of an array import java.util.*; public class ArrayIterator<T> implements Iterator<T> { // Attributes private int count; // number of elements in collection private int current; // current position in the iteration private T[ ] items; // items in the collection // Constructor: sets up this iterator using the // specified items public ArrayIterator (T[ ] collection, int size) { items = collection; count = size; current = 0; } // cont’d.. ArrayIterator.java 2-7

ArrayIterator.java (cont’d) // Returns true if this iterator has at least one // more element to deliver in the iteration public boolean hasNext( ) { return (current < count); } // Returns the next element in the iteration. // If there are no more elements in this iteration, // throws an exception. public T next( ) { if (! hasNext( )) throw new NoSuchElementException( ); current++; return items[current - 1]; ArrayIterator.java (cont’d) 2-8

Linked Iterator If we had a collection with a linked implementation, we would need a linked implementation of the Iterator interface See LinkedIterator.java Its attributes Its constructor The code for the methods hasNext and next In what order does it deliver the items? Note: LinkedIterator.java can be used by a linked implementation of any collection!

LinkedIterator.java import java.util.*; public class LinkedIterator<T> implements Iterator<T> { // Attributes private int count; // number of elements in collection private LinearNode<T> current; // current position // Constructor: Sets up this iterator using the specified items public LinkedIterator (LinearNode<T> collection, int size){ current = collection; count = size; } //cont’d.. LinkedIterator.java

LinkedIterator.java (cont’d) // Returns true if this iterator has at least one more element // to deliver in the iteration. public boolean hasNext( ) { return (current!= null); } // Returns the next element in the iteration. If there are no // more elements in this iteration, throws an exception. public T next( ) { if (! hasNext( )) throw new NoSuchElementException( ); T result = current.getElement( ); current = current.getNext( ); return result; LinkedIterator.java (cont’d)

Iterators for a Collection So how do we set up an iterator for a collection? Recall that the ListADT interface has an operation called iterator : // Returns an iterator for the elements in this list public Iterator<T> iterator( ); (In fact, any of our collections could have had an iterator operation … later)

The iterator Operation in the ListADT Note that the return type of the iterator operation is Iterator<T> But Iterator<T> is an interface, not a class! When the return type of a method is an interface name, the method actually returns an object from a class that implements the interface The iterator operation in ArrayList will use the class ArrayIterator The iterator operation in LinkedList will use the class LinkedIterator

iterator method for ArrayList /** * Returns an iterator for the elements currently in this list. * * @return an iterator for the elements in this list */ public Iterator<T> iterator() { return new ArrayIterator<T> (list, rear); } 2-14

iterator method for LinkedList /** * Returns an iterator for the elements currently in this list. * * @return an iterator for the elements in this list */ public Iterator<T> iterator( ) { return new LinkedIterator<T> (contents, count); } The only difference from the iterator method in ArrayList is the class from which the iterator object is being created!

Using an Iterator When the iterator() method in a collection is invoked, it returns an “iterator object” We can then invoke the methods hasNext() and next() on that object, to iterate through the collection (Those are the methods that are specified in the Iterator<T> interface)

Using an Iterator in an Application Example: Suppose we had an unordered list that was created by ArrayUnorderedList<Person> myList = new ArrayUnorderedList<Person>(); and then had items added to it… // Use iterator to display contents of list Iterator<Person> iter = myList.iterator();  while(iter.hasNext() ) {     System.out.println(iter.next()); }  // cont’d

Using an Iterator in an Application // Print just the email addresses now // Note that we have to start a new iteration! iter = myList.iterator(); // start new iteration  while(iter.hasNext() ) { System.out.println(iter.next().getEmail()); }

Example: Using an Iterator within a Class Definition Rewrite the toString() method of ArrayList using its iterator: public String toString() { String result = “”; Iterator<T> iter = this.iterator(); while ( iter.hasNext() ) result = result + iter.next().toString() + “\n”; return result; } 2-19

Discussion Could we use the very same code from the previous slide for the toString() method of LinkedList? If we had an iterator operation in the StackADT, could we use this very same code for the toString() methods of the StackADT implementations?

Exercises Add an iterator operation to the StackADT Implement it in ArrayStack In what order will it deliver the items if we use ArrayIterator.java to implement the Iterator<T> interface? Implement it in LinkedStack In what order will it deliver the items if we use LinkedIterator.java to implement the Iterator<T> interface? Rewrite the toString method of the StackADT implementations to use its iterator Ditto for the QueueADT

Discussion Note that the order of the iteration is determined by the design of the class that implements the Iterator<T> interface If we wanted an iterator that delivered the items in a stack in the opposite order from ArrayIterator, what would we have to do?

Why use Iterators? Traversing through the elements of a collection is very common in programming, and iterators provide a uniform way of doing so Advantage? Using an iterator, we don’t need to know how the collection is implemented! 2-23