Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
Linked Lists Linear collections.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Double-Linked Lists and Circular Lists
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
Chapter 7 Iterators Modified. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using.
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall Office hours: M-F 11:00-11:
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.
CS 280 Data Structures Professor John Peterson. Project 9 Questions? IS280.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
1 Topic 8 Iterators "First things first, but not necessarily in that order " -Dr. Who.
CS 307 Fundamentals of Computer ScienceIterators 1 Topic 14 Iterators "First things first, but not necessarily in that order " -Dr. Who.
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.
Arrays And ArrayLists - S. Kelly-Bootle
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Problem Of The Day  Decipher the following phrase: STANDS 0 _
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
LinkedList Many slides from Horstmann modified by Dr V.
1 Iterators "First things first, but not necessarily in that order " -Dr. Who CS Computer Science II.
Information and Computer Sciences University of Hawaii, Manoa
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
Today’s Agenda  Generic  Iterators CS2336: Computer Science II.
Week 4 - Monday.  What did we talk about last time?  Queues  Implementing queues with circular arrays.
Using Iterators Trey Chandler Burlington Williams High School Mr. Langner’s Class,
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 16 – Basic Data Structures.
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
CSC 212 – Data Structures Lecture 23: Iterators. Question of the Day Thieves guild states it will sell to members: lock picking kits  $0.67 each 40’
Recursive Objects (Part 2) 1. Adding to the front of the list  adding to the front of the list  t.addFirst('z') or t.add(0, 'z') 2 'a' 'x' LinkedList.
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.
Iterator Pattern. Traversing two different collections  When bringing two previously developed objects together, it can be difficult to change an implementation.
Iteration Abstraction SWE Software Construction Fall 2009.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
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.
CS 46B: Introduction to Data Structures July 21 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
1 Example: LinkedStack LinkedStack UML Class Diagram LinkedStack Class LinkedStack Attributes/Constructor LinkedStack Methods LinkedStack iterator method.
Recursive Objects Singly Linked List (Part 2) 1. Operations at the head of the list  operations at the head of the list require special handling because.
1 Iterator Pattern (A Behavioral Pattern) Prepared by: Neha Tomar.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
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 Data Structures
EKT472: Object Oriented Programming
Iterators.
Lecture 15: More Iterators
Chapter 16 Iterators.
Iteration Abstraction
"First things first, but not necessarily in that order " -Dr. Who
ArraySet Methods and ArrayIterator
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Copyright ©2012 by Pearson Education, Inc. All rights reserved
"First things first, but not necessarily in that order." -Dr. Who
Iteration Abstraction
Example: LinkedSet<T>
Interator and Iterable
"First things first, but not necessarily in that order " -Dr. Who
"First things first, but not necessarily in that order " -Dr. Who
slides created by Alyssa Harding
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

Iterators

Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).

Iterator  Interface defined in java.util.Iterator For simplicity, we will discuss the non- parameterized version of java.util.Iterator.For simplicity, we will discuss the non- parameterized version of java.util.Iterator. We will also implement our iterator as a public inner class of our linked list.We will also implement our iterator as a public inner class of our linked list.

Iterator  Methods required by java.util.iterator: 1.public void remove ( ) 2.public Object next ( ) 3.public boolean hasNext ( )

Iterator  public void remove ( ) optionaloptional removes from the collection the last element returned by nextremoves from the collection the last element returned by next this method can be called only once per call to next()this method can be called only once per call to next() if the collection is changed in any way, other than by using remove, the behavior of the iterator is not specified (and thus should be considered unpredictable)if the collection is changed in any way, other than by using remove, the behavior of the iterator is not specified (and thus should be considered unpredictable) throws IllegalStateException if the next() method has not yet been called, or if the remove() method has already been called after the last call to the next() methodthrows IllegalStateException if the next() method has not yet been called, or if the remove() method has already been called after the last call to the next() method throws UnsupportedOperationException if the remove operation is not supported by this iteratorthrows UnsupportedOperationException if the remove operation is not supported by this iterator

Iterator  public Object next ( ) returns the next element of the collection that produced the iteratorreturns the next element of the collection that produced the iterator throws a NoSuchElementException if there is no next elementthrows a NoSuchElementException if there is no next element

Iterator  public boolean hasNext ( ) returns true if next() has not yet returned all the elements in the collectionreturns true if next() has not yet returned all the elements in the collection returns false otherwisereturns false otherwise

Our iterator public class MyListWithIterator { private class Node { private class Node { String mData=""; String mData=""; Node mNext=null; Node mNext=null; private Node ( String data ) { private Node ( String data ) { mData = data; mData = data; } } // // public class Iterator implements java.util.Iterator { public class Iterator implements java.util.Iterator { public void remove ( ) { //optional public void remove ( ) { //optional } public Object next ( ) { public Object next ( ) { } public boolean hasNext ( ) { public boolean hasNext ( ) { } } // // private Node mHead=null; private Node mHead=null; public void add ( String s ) { public void add ( String s ) { Node n = new Node( s ); Node n = new Node( s ); n.mNext = mHead; n.mNext = mHead; mHead = n; mHead = n; } public Iterator iterator ( ) { public Iterator iterator ( ) { return new Iterator(); return new Iterator(); }} Inner class Node definition that we developed previously.

Our iterator public class MyListWithIterator { private class Node { private class Node { String mData=""; String mData=""; Node mNext=null; Node mNext=null; private Node ( String data ) { private Node ( String data ) { mData = data; mData = data; } } // // public class Iterator implements java.util.Iterator { public class Iterator implements java.util.Iterator { public void remove ( ) { //optional public void remove ( ) { //optional } public Object next ( ) { public Object next ( ) { } public boolean hasNext ( ) { public boolean hasNext ( ) { } } // // private Node mHead=null; private Node mHead=null; public void add ( String s ) { public void add ( String s ) { Node n = new Node( s ); Node n = new Node( s ); n.mNext = mHead; n.mNext = mHead; mHead = n; mHead = n; } public Iterator iterator ( ) { public Iterator iterator ( ) { return new Iterator(); return new Iterator(); }} Inner class Iterator definition with interface methods defined.

Our iterator public class MyListWithIterator { private class Node { private class Node { String mData=""; String mData=""; Node mNext=null; Node mNext=null; private Node ( String data ) { private Node ( String data ) { mData = data; mData = data; } } // // public class Iterator implements java.util.Iterator { public class Iterator implements java.util.Iterator { public void remove ( ) { //optional public void remove ( ) { //optional } public Object next ( ) { public Object next ( ) { } public boolean hasNext ( ) { public boolean hasNext ( ) { } } // // private Node mHead=null; private Node mHead=null; public void add ( String s ) { public void add ( String s ) { Node n = new Node( s ); Node n = new Node( s ); n.mNext = mHead; n.mNext = mHead; mHead = n; mHead = n; } public Iterator iterator ( ) { public Iterator iterator ( ) { return new Iterator(); return new Iterator(); }} The head of our linked list.

Our iterator public class MyListWithIterator { private class Node { private class Node { String mData=""; String mData=""; Node mNext=null; Node mNext=null; private Node ( String data ) { private Node ( String data ) { mData = data; mData = data; } } // // public class Iterator implements java.util.Iterator { public class Iterator implements java.util.Iterator { public void remove ( ) { //optional public void remove ( ) { //optional } public Object next ( ) { public Object next ( ) { } public boolean hasNext ( ) { public boolean hasNext ( ) { } } // // private Node mHead=null; private Node mHead=null; public void add ( String s ) { public void add ( String s ) { Node n = new Node( s ); Node n = new Node( s ); n.mNext = mHead; n.mNext = mHead; mHead = n; mHead = n; } public Iterator iterator ( ) { public Iterator iterator ( ) { return new Iterator(); return new Iterator(); }} A method to add elements to our linked list (as before).

Our iterator public class MyListWithIterator { private class Node { private class Node { String mData=""; String mData=""; Node mNext=null; Node mNext=null; private Node ( String data ) { private Node ( String data ) { mData = data; mData = data; } } // // public class Iterator implements java.util.Iterator { public class Iterator implements java.util.Iterator { public void remove ( ) { //optional public void remove ( ) { //optional } public Object next ( ) { public Object next ( ) { } public boolean hasNext ( ) { public boolean hasNext ( ) { } } // // private Node mHead=null; private Node mHead=null; public void add ( String s ) { public void add ( String s ) { Node n = new Node( s ); Node n = new Node( s ); n.mNext = mHead; n.mNext = mHead; mHead = n; mHead = n; } public Iterator iterator ( ) { public Iterator iterator ( ) { return new Iterator(); return new Iterator(); }} New: A public method that returns an iterator for a specific linked list instance.

Our iterator public class Iterator implements java.util.Iterator { public class Iterator implements java.util.Iterator { private Node mNextElement = mHead; private Node mNextElement = mHead; // // public void remove ( ) { //optional public void remove ( ) { //optional throw new UnsupportedOperationException(); throw new UnsupportedOperationException(); } // // public Object next ( ) { public Object next ( ) { } // // public boolean hasNext ( ) { public boolean hasNext ( ) { } } We need something to keep track of where we are as we iterate through the list.

Our iterator public class Iterator implements java.util.Iterator { public class Iterator implements java.util.Iterator { private Node mNextElement = mHead; private Node mNextElement = mHead; // // //removes from the collection the last element returned by next. //removes from the collection the last element returned by next. //this method can be called only once per call to next(). If the //this method can be called only once per call to next(). If the // collection is changed in any way, other than by using remove, the // collection is changed in any way, other than by using remove, the // behavior of the iterator is not specified (and thus should be // behavior of the iterator is not specified (and thus should be // considered unpredictable). // considered unpredictable). //throws IllegalStateException if the next() method has not yet been //throws IllegalStateException if the next() method has not yet been // called, or if the remove() method has already been called after // called, or if the remove() method has already been called after // the last call to the next() method. // the last call to the next() method. //throws UnsupportedOperationException if the remove operation is not //throws UnsupportedOperationException if the remove operation is not // supported by this iterator. // supported by this iterator. public void remove ( ) { //optional public void remove ( ) { //optional throw new UnsupportedOperationException(); throw new UnsupportedOperationException(); } // // public Object next ( ) { public Object next ( ) { } // // public boolean hasNext ( ) { public boolean hasNext ( ) { } } Since remove() is optional, we will through the indicated exception. It will be left as an exercise to the reader.

Our iterator public class Iterator implements java.util.Iterator { public class Iterator implements java.util.Iterator { private Node mNextElement = mHead; private Node mNextElement = mHead; // // public void remove ( ) { //optional public void remove ( ) { //optional throw new UnsupportedOperationException(); throw new UnsupportedOperationException(); } // // //returns the next element of the collection that produced the //returns the next element of the collection that produced the // iterator. // iterator. //throws a NoSuchElementException if there is no next element. //throws a NoSuchElementException if there is no next element. public Object next ( ) { public Object next ( ) { if (mNextElement==null) if (mNextElement==null) throw new java.util.NoSuchElementException(); throw new java.util.NoSuchElementException(); String temp = mNextElement.mData; String temp = mNextElement.mData; mNextElement = mNextElement.mNext; mNextElement = mNextElement.mNext; return temp; return temp; } // // public boolean hasNext ( ) { public boolean hasNext ( ) { } } Make a copy of the next string, move on to the next item, and return the string. Privacy leak possible?

Our iterator public class Iterator implements java.util.Iterator { public class Iterator implements java.util.Iterator { private Node mNextElement = mHead; private Node mNextElement = mHead; public void remove ( ) { //optional public void remove ( ) { //optional throw new UnsupportedOperationException(); throw new UnsupportedOperationException(); } // // public Object next ( ) { public Object next ( ) { if (mNextElement==null) if (mNextElement==null) throw new java.util.NoSuchElementException(); throw new java.util.NoSuchElementException(); String temp = mNextElement.mData; String temp = mNextElement.mData; mNextElement = mNextElement.mNext; mNextElement = mNextElement.mNext; return temp; return temp; } // // //returns true if next() has not yet returned all the elements //returns true if next() has not yet returned all the elements // in the collection; returns false otherwise. // in the collection; returns false otherwise. public boolean hasNext ( ) { public boolean hasNext ( ) { return (mNextElement != null); return (mNextElement != null); } } When next is null, there is nothing left.

Using our iterator public static void main ( String args[] ) { public static void main ( String args[] ) { MyListWithIterator list = new MyListWithIterator(); MyListWithIterator list = new MyListWithIterator(); list.add( "fred" ); list.add( "fred" ); list.add( "sally" ); list.add( "sally" ); MyListWithIterator.Iterator it = list.iterator(); MyListWithIterator.Iterator it = list.iterator(); while (it.hasNext()) { while (it.hasNext()) { System.out.println( it.next() ); System.out.println( it.next() ); } }

Our complete iterator public class MyListWithIterator { private class Node { private class Node { String mData=""; String mData=""; Node mNext=null; Node mNext=null; private Node ( String data ) { private Node ( String data ) { mData = data; mData = data; } } // // public class Iterator implements java.util.Iterator { public class Iterator implements java.util.Iterator { private Node mNextElement = mHead; private Node mNextElement = mHead; // // //removes from the collection the last element returned by next. //removes from the collection the last element returned by next. //this method can be called only once per call to next(). If the //this method can be called only once per call to next(). If the // collection is changed in any way, other than by using remove, the // collection is changed in any way, other than by using remove, the // behavior of the iterator is not specified (and thus should be // behavior of the iterator is not specified (and thus should be // considered unpredictable). // considered unpredictable). //throws IllegalStateException if the next() method has not yet been //throws IllegalStateException if the next() method has not yet been // called, or if the remove() method has already been called after // called, or if the remove() method has already been called after // the last call to the next() method. // the last call to the next() method. //throws UnsupportedOperationException if the remove operation is not //throws UnsupportedOperationException if the remove operation is not // supported by this iterator. // supported by this iterator. public void remove ( ) { //optional public void remove ( ) { //optional throw new UnsupportedOperationException(); throw new UnsupportedOperationException(); } // // //returns the next element of the collection that produced the //returns the next element of the collection that produced the // iterator. // iterator. //throws a NoSuchElementException if there is no next element. //throws a NoSuchElementException if there is no next element. public Object next ( ) { public Object next ( ) { if (mNextElement==null) if (mNextElement==null) throw new java.util.NoSuchElementException(); throw new java.util.NoSuchElementException(); String temp = mNextElement.mData; String temp = mNextElement.mData; mNextElement = mNextElement.mNext; mNextElement = mNextElement.mNext; return temp; return temp; } // // //returns true if next() has not yet returned all the elements //returns true if next() has not yet returned all the elements // in the collection; returns false otherwise. // in the collection; returns false otherwise. public boolean hasNext ( ) { public boolean hasNext ( ) { return (mNextElement != null); return (mNextElement != null); } } // // private Node mHead=null; private Node mHead=null; // // public void add ( String s ) { public void add ( String s ) { Node n = new Node( s ); Node n = new Node( s ); n.mNext = mHead; n.mNext = mHead; mHead = n; mHead = n; } // // public Iterator iterator ( ) { public Iterator iterator ( ) { return new Iterator(); return new Iterator(); } // // public static void main ( String args[] ) { public static void main ( String args[] ) { MyListWithIterator list = new MyListWithIterator(); MyListWithIterator list = new MyListWithIterator(); list.add( "fred" ); list.add( "fred" ); list.add( "sally" ); list.add( "sally" ); MyListWithIterator.Iterator it = list.iterator(); MyListWithIterator.Iterator it = list.iterator(); while (it.hasNext()) { while (it.hasNext()) { System.out.println( it.next() ); System.out.println( it.next() ); } }} This is too small to read but is provided in its entirety so that you may cut and paste it into your own code if you wish.

Our linked list and the for-each loop  To use our linked list class and our iterator with the for-each loop, we must first implement the java.util.Collection interface (along with the methods that this interface requires).  Then we may state: for (Object s : list) System.out.println( s ); System.out.println( s ); Note Object s above. String s will cause the compiler to issue an error.Note Object s above. String s will cause the compiler to issue an error.