1 Lecture 09 Iterators and Enumerations Reading for these lectures: Weiss, Section 6.3.2 Iterator Interface. Much better is: ProgramLive, Section 12.3.

Slides:



Advertisements
Similar presentations
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)
Advertisements

COSC 1P03 Data Structures and Abstraction 10.1 The List If A is success in life, then A equals x plus y plus z. Work is x; y is play; and z is keeping.
Data Structures1 Basic Data Structures Elementary Structures Arrays Lists Search Structures Binary search Tree Hash Tables Sequence Structures Stacks Queues.
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.
Java Programming Abstract classes and Interfaces.
CS18000: Problem Solving and Object-Oriented Programming.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Elementary Data Structures CS 110: Data Structures and Algorithms First Semester,
COP3538 – Data Structures Using OOP Chapter 4 – Stacks and Queues.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Lecture 17 Abstract classes Interfaces The Comparable interface Event listeners All in chapter 10: please read it.
Introduction to Stacks What is a Stack Stack implementation using arrays. Application of Stack.
1 Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p no multiple inheritance with classes public class.
Introduction to Stacks What are Stacks? Stack implementation using arrays. Stack application.
Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
1 CS211, Lecture 20 Priority queues and Heaps Readings: Weiss, sec. 6.9, secs When they've got two queues going, there's never any queue!
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.
1 Lecture 07 Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p ProgramLive, Section 12.1 In User Interface.
CS 307 Fundamentals of Computer ScienceInterfaces and Abstract Classes 1 Topic 7 Interfaces and Abstract Classes “I prefer Agassiz in the abstract, rather.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
(c) University of Washington14-1 CSC 143 Java Collections.
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Chapter 18 Java Collections Framework
LinkedList Many slides from Horstmann modified by Dr V.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
18-1 Queues Data Structures and Design with Java and JUnit © Rick Mercer.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
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.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Generic Programming and Inner classes ge·ner·ic 1a : relating or applied to or descriptive of all members of a genus, species, class, or group : common.
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.
Today’s lecture Review of chapter 8 Go over examples.
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.
“The desire for safety stands against every great and noble enterprise.” – Tacitus Thought for the Day.
Vector program patterns Vectors contain many elements, so loops are common. Counted processing // Print the first 3 elements. for (int i = 0; i < 3; i++)
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 9 Doubly Linked Lists and Ordered Lists Lecture.
C19: Collection Classes (don’t forget to look at all the online code examples)
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Object Oriented Programming in Java Habib Rostami Lecture 7.
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
Click to edit Master text styles Stacks Data Structure.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
CS/ENGRD 2110 Spring 2017 Lecture 7: Interfaces and Abstract Classes
Lecture 10 Review of classes
Recap: Solution of Last Lecture Activity
CS/ENGRD 2110 fall 2017 Lecture 7: Interfaces and Abstract Classes
List Representation - Array
Iteration Abstraction
null, true, and false are also reserved.
Lecture 5 Stacks King Fahd University of Petroleum & Minerals
CS/ENGRD 2110 fall 2017 Lecture 7: Interfaces and Abstract Classes
Iteration Abstraction
CS/ENGRD 2110 Spring 2019 Lecture 7: Interfaces and Abstract Classes
Introduction to Stacks
Introduction to Stacks
Presentation transcript:

1 Lecture 09 Iterators and Enumerations Reading for these lectures: Weiss, Section Iterator Interface. Much better is: ProgramLive, Section The introduction of suitable abstractions is our only mental aid to reduce the appeal to enumeration, to organize and master complexity. Edsger W. Dijkstra Incrementing C by 1 is not enough to make a good object-oriented language. M. Sakkinen (in C, C++, and Java, x++ adds 1 to x.)

2 Practice practice practice It will help you tremendously to download the programs that we look at today and experiment with them. It will help to write a few implementations of class Iterator yourself and test them. Examples: An Iterator of the digits in a String, producing objects of class Integer. An Iterator of the prime numbers. An Iterator of the chars of a String from end to beginning. An Iterator for the Fibonacci numbers.

3 Abstract data type Type: a bunch of values together with operations on them. We can write an interface that DEFINES such a type. We call it an “abstract data type” because we don’t give a concrete implementation of it, we just define it “abstractly”

4 Type 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 but ambiguous. Doesn’t say which item to delete or where to add an item.

5 Implement 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.

6 Class invariant: describes the fields and the 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; }

7 public 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 Comparable

8 public 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 compareTo We look at a DrJava program that has abstract class Shape with two subclasses, Square and Circle. A main program creates an array of 8 shapes and sorts them. This illustrates nicely how the interface Comparable is used. ob is cast to Shape

9 Objects from the Shape Demo a0 Shape getArea() compareTo(Object) getPerimeter() Circle a1 Shape getArea() compareTo(Object) getPerimeter() Square radius 2.0 side 4.0 Circle(double) getRadius() getArea() getPerimeter() toString() Square(double) getSide() getArea() getPerimeter() toString() b a3 a0a1a6a2a7 a9a8 b[i].compareTo(b[p]) i p

10 Interface Iterator in package java.util. (From dictionary) Enumeration: an itemized list. Enumerate: to relate one after another. It is not necessary to enumerate all the bitter and factious disputes that marked this unhappy quarter century He enumerated the advantages of his new position. He enumerated the necessary qualities of a good general A class that extends iterator is used to make it easy to write loops to enumerate a list of values.

11 public 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 Iterator in 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 iterator Create an instance of EnumerateEvens Typical loop: each iteration gets a new item and processes it. ALWAYS test whether there is another item before getting it.

14 public 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 letters in s */ public LetterEnum(String s) { this.s= s; k= 0; } /** = "there is another item to enumerate" */ public boolean hasNext() { while (k != s.length() && !Character.isLetter(s.charAt(k))) { k= k+1; } return k < s.length(); } /** = the next item to enumerate. Throw a NoSuchElementException if there is none.*/ public Object next() { if (!hasNext()) return new NoSuchElementException(); k= k+1; return new Character(s.charAt(k-1)); } Iterator to enumerate letters in a string

15 public 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().*/ /** = "there is another item to enumerate" */ public boolean hasNext() { while (k != s.length() && !Character.isLetter(s.charAt(k))) { k= k+1; } return k < s.length(); } Iterator to enumerate letters in a string Calling hasNext has a benevolent side-effect: it sets k to index of next item to be enumerated. If k is already contains that index, then hasNext does not change k!!! The last statement is important.

16 /** = a string that contains the items enumerated by it, separated by "," and delimited by "[" and "]" */ public static String toString(Iterator it) { String res= "["; while (it.hasNext()) { if (res.length() > 1) res= res + ","; res= res + it.next(); } return res + "]"; } A method to produce a string that contains all the items enumerated by any Iterator!!!