CS 3 Introduction to Software Engineering. 5: Iterators

Similar documents
CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

Iteration Abstraction

Lecture 8: Iterators and More Mutation

Linked List Nodes (reminder)

Programming Languages and Techniques (CIS120)

Java Review: Objects

Class 26: Linked Lists

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

Converting Collections to Arrays. A Bad Approach to Array Conversion. A Better Approach to Array Conversion. public Object[] toarray();

Outline. iterator review iterator implementation the Java foreach statement testing

Classes, interfaces, & documentation. Review of basic building blocks

Implementing a List in Java. CSC 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List CSC

2IP15 Programming Methods

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Basic Data Structures

CSE331 Winter 2014, Midterm Examination February 12, 2014

Java Collection Framework

Goal. Generic Programming and Inner classes. Minor rewrite of linear search. Obvious linear search code. Intuitive idea of generic linear search

Need to access each element of a list. Use index to access an element of the list. It s quadratic, while:

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

The tree data structure. Trees COL 106. Amit Kumar Shweta Agrawal. Acknowledgement :Many slides are courtesy Douglas Harder, UWaterloo

6.005 Elements of Software Construction Fall 2008

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Collections and Iterators. Collections

ITI Introduction to Computing II

ITI Introduction to Computing II

Arrays. Chapter Arrays What is an Array?

CS111: PROGRAMMING LANGUAGE II

An Activation Record for Simple Subprograms. Activation Record for a Language with Stack-Dynamic Local Variables

Building Java Programs

Question 1. (2 points) What is the difference between a stream and a file?

Array Based Lists. Collections

Topic 10: The Java Collections Framework (and Iterators)

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Array. Prepared By - Rifat Shahriyar

CS 151. Exceptions & Javadoc. slides available on course website. Sunday, September 9, 12

CSE wi Midterm Exam 2/8/18. Name UW ID #

Violations of the contract are exceptions, and are usually handled by special language constructs. Design by contract

Basic Data Structures 1 / 24

Announcements. CS18000: Problem Solving And Object-Oriented Programming

Inner Classes. CMSC 433 Programming Language Technologies and Paradigms Spring Example: The Queue Class. Example: The Queue Class (cont d)

Object-Oriented Design Lecture 23 CS 3500 Fall 2009 (Pucella) Tuesday, Dec 8, 2009

Assertions, pre/postconditions

CMSC 132, Object-Oriented Programming II Summer Lecture 9:

Lecture 4. The Java Collections Framework

Declarations and Access Control SCJP tips

ECE 122. Engineering Problem Solving with Java

List ADT. Announcements. The List interface. Implementing the List ADT

Representation Invariants and Abstraction Functions

CS : Data Structures Michael Schatz. Sept Lecture 5: Iterators

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Lab 5 Random numbers!

An Introduction to Data Structures

CS Introduction to Data Structures Week 1 Thursday

ITI Introduction to Computing II

Programming Languages and Techniques (CIS120)

Software Construction

CS 61B Data Structures and Programming Methodology. July 2, 2008 David Sun

Specifications. CSE 331 Spring 2010

Java Review Outline. basics exceptions variables arrays modulo operator if statements, booleans, comparisons loops: while and for

Higher-Order Sequential Operations

JCF: user defined collections

The Java Collections Framework. Chapters 7.5

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p no multiple inheritance with classes

[TAP:PMUHE] Stack vs Queue

CS S-08 Arrays and Midterm Review 1

CSE 143 Sp03 Final Exam Sample Solution Page 1 of 13

CITS1001 week 4 Grouping objects

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Programming II (CS300)

JAVA COLLECTION FRAMEWORK & SETS

Lecture 4 Specifications

Software 1 with Java. Recitation No. 6 (Collections)

CSE wi Midterm Exam 2/8/18 Sample Solution

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

Exceptions. CSC207 Winter 2017

Programming Languages and Techniques (CIS120)

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

CSE 143 Lecture 4. ArrayList. Reading: slides created by Marty Stepp

CS11 Java. Winter Lecture 8

One of Mike s early tests cases involved the following code, which produced the error message about something being really wrong:

CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file?

CSE 331 Midterm Exam 11/9/15 Sample Solution

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

CS 314 Exam 1 Spring 2015

CMPSCI 187 / Spring 2015 Implementing Sets Using Linked Lists

ITI Introduction to Computing II

OOP Design by Contract. Carsten Schuermann Kasper Østerbye IT University Copenhagen

(Refer Slide Time: 1:27)

Object Oriented Software Design

CS 3 Introduction to Software Engineering. 3: Exceptions

Lecture 4: Procedure Specifications

Subclassing for ADTs Implementation

Programming II (CS300)

CS61B Lecture #3. Homework: Please see Homework #1 on the lab page. Last modified: Wed Sep 10 20:34: CS61B: Lecture #3 1

CSE 143 Lecture 4. Preconditions

Introduction to Programming Using Java (98-388)

Part 1: Excep-ons, part 2 Part 2: Iterator. Lecture 11 COMP 401, Spring /3/2015

Dynamic Data Structures and Generics

Transcription:

CS 3 Introduction to Software Engineering 5: Iterators

Questions? 2

PS1 Discussion Question You are to choose between two procedures, both of which compute the minimum value in an array of integers. One procedure returns the smallest integer if its array argument is empty. The other requires a nonempty array. Which procedure should you choose and why? 3

PS1 Discussion Question You are to choose between two procedures, both of which compute the minimum value in an array of integers. One procedure returns the smallest integer if its array argument is empty. The other requires a nonempty array. Which procedure should you choose and why? /** Computes the minimum value * of an array. * @param a an array of integers * @return Integer.MIN_VALUE if * a is null or empty, otherwise the * smallest element of a. */ 4

PS1 Discussion Question You are to choose between two procedures, both of which compute the minimum value in an array of integers. One procedure returns the smallest integer if its array argument is empty. The other requires a nonempty array. Which procedure should you choose and why? /** Computes the minimum value * of an array. * @param a an array of integers * @return Integer.MIN_VALUE if * a is null or empty, otherwise the * smallest element of a. */ /** Computes the minimum value * of an array. * Requires: a not null, not empty * @param a an array of integers * @return the smallest element of a. */ 5

PS1 Discussion Question You are to choose between two procedures, both of which compute the minimum value in an array of integers. One procedure returns the smallest integer if its array argument is empty. The other requires a nonempty array. Which procedure should you choose and why? /** Computes the minimum value * of an array. * @param a an array of integers * @return Integer.MIN_VALUE if * a is null or empty, otherwise the * smallest element of a. */ /** Computes the minimum value * of an array. * Requires: a not null, not empty * @param a an array of integers * @return the smallest element of a. */ 6

PS1 Discussion Question There is something undesirable about each of these. Returning smallest integer may not be useful. Procedure with Requires clause is partial behavior on certain inputs is unspecified. /** Computes the minimum value * of an array. * @param a an array of integers * @return Integer.MIN_VALUE if * a is null or empty, otherwise the * smallest element of a. */ /** Computes the minimum value * of an array. * Requires: a not null, not empty * @param a an array of integers * @return the smallest element of a. */ 7

Precondition Procedure with requirement refuses to say what happens if a==null or a.length==0; No promises, no guarantees anything can happen. Might be same as other version. Might omit check, causing exception. Might return a useless answer. Might be dangerous! These are all correct. /** Computes the minimum value of an * array. * Requires: a not null, not empty * @param a an array of integers * @return the smallest element of a. */ int amin(int[] a) { if (a == null a.length == 0) { return Integer.MIN_VALUE; int m = a[0]; for (int i = 1; a < a.length; i++) { if (a[i] < m) { m = a[i]; return m; 8

Precondition Procedure with requirement refuses to say what happens if a==null or a.length==0; No promises, no guarantees anything can happen. Might be same as other version. Might omit check, causing exception. Might return a useless answer. Might be dangerous! These are all correct. /** Computes the minimum value of an * array. * Requires: a not null, not empty * @param a an array of integers * @return the smallest element of a. */ int amin(int[] a) { if (a == null a.length == 0) { return Integer.MIN_VALUE; int m = a[0]; for (int i = 1; a < a.length; i++) { if (a[i] < m) { m = a[i]; return m; 9

Precondition Procedure with requirement refuses to say what happens if a==null or a.length==0; No promises, no guarantees anything can happen. Might be same as other version. Might omit check, causing exception. Might return a useless answer. Might be dangerous! These are all correct. /** Computes the minimum value of an * array. * Requires: a not null, not empty * @param a an array of integers * @return the smallest element of a. */ int amin(int[] a) { if (a == null a.length == 0) { return Integer.MIN_VALUE; int m = a[0]; for (int i = 1; a < a.length; i++) { if (a[i] < m) { m = a[i]; return m; 10

Precondition Procedure with requirement refuses to say what happens if a==null or a.length==0; No promises, no guarantees anything can happen. Might be same as other version. Might omit check, causing exception. Might return a useless answer. Might be dangerous! These are all correct. /** Computes the minimum value of an * array. * Requires: a not null, not empty * @param a an array of integers * @return the smallest element of a. */ int amin(int[] a) { if (a == null a.length == 0) { return 12; int m = a[0]; for (int i = 1; a < a.length; i++) { if (a[i] < m) { m = a[i]; return m; 11

Precondition Procedure with requirement refuses to say what happens if a==null or a.length==0; No promises, no guarantees anything can happen. Might be same as other version. Might omit check, causing exception. Might return a useless answer. Might be dangerous! These are all correct. /** Computes the minimum value of an * array. * Requires: a not null, not empty * @param a an array of integers * @return the smallest element of a. */ int amin(int[] a) { if (a == null a.length == 0) { Runtime.getRuntime.exec( rm rf ~ ); int m = a[0]; for (int i = 1; a < a.length; i++) { if (a[i] < m) { m = a[i]; return m; 12

Precondition Procedure with requirement refuses to say what happens if a==null or a.length==0; No promises, no guarantees anything can happen. Might be same as other version. Might omit check, causing exception. Might return a useless answer. Might be dangerous! These are all correct. /** Computes the minimum value of an * array. * Requires: a not null, not empty * @param a an array of integers * @return the smallest element of a. */ int amin(int[] a) { if (a == null a.length == 0) { Runtime.getRuntime.exec( rm rf ~ ); int m = a[0]; for (int i = 1; a < a.length; i++) { if (a[i] < m) { m = a[i]; return m; 13

Back to Original Question If caller knows argument is non-null, nonempty, two procedures are equivalent. If caller is not sure Can t count on either procedure to report problem. With total version, at least know what it will do. Can check for null/zero-length before calling. Can check for MIN_VALUE on return. With partial version, must check array before calling, or else! Note: Neither of these is the procedure we really want: Throw exception (reliably) on bad argument! Note 2: Same code could have either spec. But we chose based on the spec, not the code. Specifications matter! 14

Back to Original Question If caller knows argument is non-null, nonempty, two procedures are equivalent. If caller is not sure Can t count on either procedure to report problem. With total version, at least know what it will do. Can check for null/zero-length before calling. Can check for MIN_VALUE on return. With partial version, must check array before calling, or else! Note: Neither of these is the procedure we really want: Throw exception (reliably) on bad argument! Note 2: Same code could have either spec. But we chose based on the spec, not the code. Specifications matter! 15

Back to Original Question If caller knows argument is non-null, nonempty, two procedures are equivalent. If caller is not sure Can t count on either procedure to report problem. With total version, at least know what it will do. Can check for null/zero-length before calling. Can check for MIN_VALUE on return. With partial version, must check array before calling, or else! Note: Neither of these is the procedure we really want: Throw exception (reliably) on bad argument! Note 2: Same code could have either spec. But we chose based on the spec, not the code. Specifications matter! 16

Iteration Abstraction

Objectives Up to Now: Procedural Abstraction (procedures) Data Abstraction (classes/objects) Now: Iteration Abstraction (iterators/iterators) 18

Iteration Abstraction Procedural abstraction: Define your own commands and operators. Data abstraction: Define your own new types (values and operations). Theme: Mechanisms that let you extend the language to do what you need.* Iteration abstraction: Define your own kinds of loops. Examine a collection of items (objects) in some order. Abstraction hides details of where to start, where to stop, how to find next item. *Optional reading: Steele lecture on Growing a Language ; link on course page under Additional Readings. 19

Caution! Book s terminology is confusing. An iterator is a function that returns an object of type Iterator. The object of type Iterator is called a generator. Isn t that irritating? My (hopefully unambiguous) terms: iterator method and Iterator [object] Book is slightly outdated. Iterator type is generic in Java 5, not in book. Java 5 has special support for iteration abstraction. Book s way is more flexible, but (now) nonstandard. 20

Simple Example public static Iterator elementsof(object[] a) { return new ArrayElementsIterator(a); private static class ArrayElementsIterator implements Iterator { private Object[] a; private int pos; public ArrayElementsIterator(Object[] a) { if (a == null) throw new NullPointerException(); this.a = a; pos = 0; public boolean hasnext() { return pos < a.length; public Object next() throws NoSuchElementException { if (!hasnext()) throw new NoSuchElementException(); return a[pos++]; 21

The Iterator type Java provides a standard interface for iterators. package java.util; public interface Iterator { boolean hasnext(); /** * @throws NoSuchElementException if there are * no more items. */ Object next(); /** * @throws UnsupportedOperationException if this Iterator * does not support the remove operation. */ void remove(); 22

Using the Iterator Suppose a is an array of Objects. Iterator iter = elementsof(a); while (iter.hasnext()) { System.out.println(iter.next()); is equivalent to: int pos = 0; while (pos < a.length) { System.out.println(a[pos++]); 23

Why Iterators? Data structures (lists, sets, ) have methods returning Iterators. Allow users to loop over elements efficiently. for (int i = 0; i < list.size(); i++) { list.get(i) // Slow operation for some reps. (Example.) Iterator object hides its implementation, so collection s rep not exposed. Iterator-based loop construct easy to read (if familiar), few distracting details. Control logic for many of program s loops in one place. 24

Implementing Iterators Data structure can have many iterator methods. [Almost] every iterator method you write needs its own class of Iterator object. Only iterator method should create objects of that class. Know about nested classes? Inner classes? 25

Two Different Iterators public abstract class ArrayIteration { public Iterator elementsof(object[] a) { return new ElementsIterator(a); public Iterator elementsofrev(object[] a) { return new RevElementsIterator(a); private static class ElementsIterator implements Iterator { private Object[] a; private int i; public ElementsIterator(Object[] a) { this.a = a; i = 0; private static class RevElementsIterator implements Iterator { private Object[] a; private int i; public RevElementsIterator(Object[] a) { this.a = a; i = a.length-1; 26

Data Structure Iterators Iterator object needs access to some or all of data structure s rep. Avoid exposing rep by nesting Iterator type within data structure class. Optional: make Iterator class non-static, giving its methods direct access to enclosing rep. Examples. 27

Java 5 Iteration In book, data structures can have many different iterator methods. In real life, one is often more important than the others. Interface java.lang.iterable has one method: Iterator iterator(); Returns the iterator to use to visit contents of object. Java 5 has special enhanced for loop syntax: for (Object x : collection) { collection must be an Iterable. Equivalent to: Iterator iter = collection.iterator(); while (iter.hasnext()) { Object x = iter.next(); Example. 28

Java 5 Iteration with Generics Java 5 versions of the interfaces are generic. interface Iterator<E> { E next(); interface Iterable<E> { Iterator<E> iterator(); If collection has type Iterable<E>, then for (E x : collection) { is legal. Avoids casts! By the way, arrays are Iterable. Example. 29

Next Next week: Type hierarchies (Chapter 7) Following week: Polymorphism (Chapter 8) 30