DOC PREVIEW
CORNELL CS 211 - Lecture 9 Iterators and Enumerations

This preview shows page 1 out of 3 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 3 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 3 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

1Lecture 09 Iterators and EnumerationsReading for these lectures:Weiss, Section 6.3.2 Iterator Interface.Much better is: ProgramLive, Section 12.3.The introduction of suitable abstractions isour only mental aid to reduce the appeal toenumeration, to organize and mastercomplexity. Edsger W. DijkstraIncrementing C by 1 is not enough to makea good object-oriented language. M.Sakkinen(in C, C++, and Java, x++ adds 1 to x.)2Practice practice practiceIt will help you tremendously to downloadthe programs that we look at today andexperiment with them.It will help to write a few implementations ofclass Iterator yourself and test them.Examples:An Iterator of the digits in a String, producingobjects of class Integer.An Iterator of the prime numbers.An Iterator of the chars of a String from end tobeginning.An Iterator for the Fibonacci numbers.3Abstract data typeType: a bunch of values together withoperations on them.We can write an interface that DEFINESsuch a type. We call it an “abstract datatype” because we don’t give a concreteimplementation of it, we just define it“abstractly”4Type List211/** A list is a sequence of Objects. */public interface List211 { /** Make the list empty */ void makeEmpty(); /** Add item e to the list */ void add(Object e); /** Delete an item from the list */ void delete(); /** = an item in the list */ Object getItem(); /** = the number of items in the list */ int size();}Operations are not only abstract butambiguous. Doesn’t say which item to deleteor where to add an item.5Implement list as a stack/** An instance is a stack s of Objects */public class Stack2 implements List211 { private int N; // Maximum number of values in s private Object[] b; // Stack s is in b[0..n-1] private int n;/** Constructor: empty stack with at most N elements */ public Stack2(int N) { } /** Make the stack empty */ public void makeEmpty() { } /** add item e to the front of the stack */ public void add(Object e) { } /** delete item from the front of the stack */ public void delete() { } /** = the front item of the stack */ public Object getItem() { return null; } /** = the number of items in the stack */ public int size() { return 0; } /** = stack elements, with top first, separated by “,” and delimited by “[“ and “]” */ public String toString() { return null; }}This class is on the website. Download and play with it.6Class invariant: describes the fields andthe values they contain:/** An instance is a stack s of Objects, with a maximum size */public class Stack1 implements List211 { /** N is the max size of stack s. Stack s appears in b[0..n-1], so that s contains n items. b[0] is the bottom and b[n-1] the top of the stack*/ public Object[] b; public int n; /** Constructor: empty stack of <= m items */ public Stack1(int m) { n= m; b= new Object[m]; n= 0; }7public interface Comparable {/** = if this Object < ob then a negative integer if this Object = ob, then 0 if this Object > ob, then a positive integer */ int compareTo (Object ob);}It has ONE method, compareTo.Interface Comparable8public class Shape implements Comparable { // = if this Object < ob then a negative integer // if this Object = ob, then 0 // if this Object > ob, then a positive integer // (it’s expected that ob is really a Shape) int compareTo(Object ob) {if (this.getArea() < ((Shape)ob).getArea())return -1;if (this.getArea() ==((Shape)ob).getArea())return 0;return 1; } abstract int getArea();} (Shapes are ordered by their area)Implementing method compareToWe look at a DrJava program that hasabstract class Shape with two subclasses,Square and Circle. A main programcreates an array of 8 shapes and sortsthem. This illustrates nicely how theinterface Comparable is used.ob is castto Shape9Objects from the Shape Demoa0ShapegetArea()compareTo(Object)getPerimeter()Circlea1ShapegetArea()compareTo(Object)getPerimeter()Squareradius2.0side4.0Circle(double)getRadius()getArea()getPerimeter()toString()Square(double)getSide()getArea()getPerimeter()toString()ba3a3a0 a1 a6 a2 a7 a7 a9 a8b[i].compareTo(b[p])i p10Interface Iteratorin package java.util.(From dictionary)Enumeration: an itemized list.Enumerate: to relate one after another.It is not necessary to enumerate all the bitter andfactious disputes that marked this unhappyquarter centuryHe enumerated the advantages of his newposition.He enumerated the necessary qualities of a goodgeneralA class that extends iterator is used to makeit easy to write loops to enumerate a list ofvalues.11public interface Iterator { /** = “there are more elements to enumerate */ boolean hasNext(); /** = the next element of the enumeration. throw NoSuchElementException if there are none */ Object next(); /** remove the last element returned */ void remove();}Interface Iteratorin package java.util.12/** An enumerator for the evens in h..k */public class EvensEnum implements Iterator { private int item; /** next even int to enum. (if <= k)*/ private int k; /** enumerate the evens <= k /** Constructor: an enumerator for the evens in h..k */ public EvensEnum(int h, int k) { this.k= k; if (h % 2 == 0) item= h; else item= h+1; } /** = "there is another item to enumerate" */ public boolean hasNext() { return item <= k; } /** = the next item to enumerate. Throw a NoSuchElementException if there is none.*/ public Object next() { if (item > k) throw new NoSuchElementException(); int r= item; item= item + 2; return new Integer(r); } /** not implemented */ public void remove() {}}13/** Print out the even integers in h..k */public static void printEvens(int h, int k) { EnumerateEvens enum= new EnumerateEvens(h,k); while (enum.hasNext()) { Object ob= enum.next(); System.out.println(ob); }}Using the iteratorCreate an instance ofEnumerateEvensTypical loop: each iteration gets a newitem and processes it.ALWAYS test whether there isanother item before getting it.14public class LetterEnum implements Iterator { private String s; /** enumerate letters of s*/ private int k; /** letters in s[k..] still to be enumerated. Calling hasNext sets it to index of next letter, if there is one, or to s.length().*/ /** Constructor: an enumerator for


View Full Document

CORNELL CS 211 - Lecture 9 Iterators and Enumerations

Documents in this Course
B-Trees

B-Trees

10 pages

Hashing

Hashing

3 pages

Load more
Download Lecture 9 Iterators and Enumerations
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture 9 Iterators and Enumerations and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 9 Iterators and Enumerations 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?