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.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
The List ADT Textbook Sections
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.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Chapter 7 Iterators Modified. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using.
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.
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
OrderedListADT. Overview OrderedListADT: not the same as linked lists The OrderedListADT: operations and sample applications An ArrayList implementation.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
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.
1 Data Structures  We can now explore some advanced techniques for organizing and managing information  Chapter 12 of the book focuses on: dynamic structures.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Chapter 101 Dynamic Data Structures and Generics Chapter 10.
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
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.
Chapter 4 Linked Structures – Stacks Modified. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
LinkedList Many slides from Horstmann modified by Dr V.
Data structures Abstract data types Java classes for Data structures and ADTs.
CSS446 Spring 2014 Nan Wang  Java Collection Framework ◦ LinkedList ◦ Set ◦ Map 2.
The Java Collections Framework By the end of this lecture you should be able to: use the ArrayList class to store a list of objects; use the HashSet class.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Chapter 12: Collections by Lewis and Loftus (Updated by Dan Fleck) Coming up: Collections.
Computer Science 209 The Factory Pattern. Collections and Iterators List list1 = new ArrayList (); List list2 = new LinkedList (); Set set1 = new HashSet.
18-1 Queues Data Structures and Design with Java and JUnit © Rick Mercer.
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
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.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
CSE 373: Data Structures and Algorithms Lecture 2: Queues.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
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.
Lecture 9: Lists MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture we will learn…. ArrayList – These are re-sizeable.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
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.
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.
Iterators.
Stack: a Linked Implementation
Concepts of Programming Languages
The List ADT.
Storage Strategies: Dynamic Linking
Chapter 16 Iterators.
Chapter 7 Iterators.
ArraySet Methods and ArrayIterator
CSE 143 Lecture 27: Advanced List Implementation
Example: LinkedSet<T>
Presentation transcript:

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 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!

9-3 Motivation What if we want to traverse a collection of objects? A list, a stack, a queue … 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

Iterator Interface The Java API has a generic interface called Iterator 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

9-6 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 implements Iterator { // 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

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

9-9 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!

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

9-11 //..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)

9-12 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 iterator( ); (In fact, any of our collections could have had an iterator operation … later)

9-13 The iterator Operation in the ListADT Note that the return type of the iterator operation is Iterator But Iterator 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

/** * Returns an iterator for the elements currently in this list. * an iterator for the elements in this list */ public Iterator iterator() { return new ArrayIterator (list, rear); } iterator method for ArrayList

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

9-16 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 interface)

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

9-18 Using an Iterator in an Application // Print just the 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().get ()); }

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

9-20 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?

9-21 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 interface? Implement it in LinkedStack In what order will it deliver the items if we use LinkedIterator.java to implement the Iterator interface? Rewrite the toString method of the StackADT implementations to use its iterator Ditto for the QueueADT

9-22 Discussion Note that the order of the iteration is determined by the design of the class that implements the Iterator 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!