Iteration Abstraction SWE 619 - Software Construction Fall 2009.

Slides:



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

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++)
The Substitution Principle SWE 332 – Fall Liskov Substitution Principle In any client code, if subtype object is substituted for supertype object,
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Data Abstraction II SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
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.
Chapter 19 Java Data Structures
MIT AITI 2003 Lecture 7 Class and Object - Part I.
Iterators CS 367 – Introduction to Data Structures.
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.
CSE 143 Lecture 15 Sets and Maps; Iterators reading: ; 13.2; 15.3; 16.5 slides adapted from Marty Stepp
COMP 103 Iterators and Iterable. RECAP  Maps and Queues TODAY  Queue Methods  Iterator and Iterable 2 RECAP-TODAY.
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
Cs2220: Engineering Software Class 8: Implementing Data Abstractions Fall 2010 University of Virginia David Evans.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
(c) University of Washington14-1 CSC 143 Java Collections.
EECE 310: Software Engineering Iteration Abstraction.
Big Java Chapter 16.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Chapter 18 Java Collections Framework
1/20/03A2-1 CS494 Interfaces and Collection in Java.
CMSC 341 Linked Lists, Stacks and Queues. 8/3/2007 UMBC CMSC 341 LSQ 2 Implementing Your Own Linked List To create a doubly linked list as seen below.
09-1 Queues and List-Based ADT Implementations Problem Set: PS3 due Wednesday, March 7 Wellesley College CS230 Lecture 09 Monday, February 26 Handout #18.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
Linked Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Comp 302: Software Engineering Data Abstractions.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Computer Science 209 The Factory Pattern. Collections and Iterators List list1 = new ArrayList (); List list2 = new LinkedList (); Set set1 = new HashSet.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
Type Abstraction Liskov, Chapter 7. 2 Liskov Substitution Principle In any client code, if the supertype object is substituted by a subtype object, the.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Abstract Data Types – Examples / Summary (Based on slides by Mike Ernst and David Notkin)
Type Abstraction SWE Spring October 05Kaushik, Ammann Substitution Principle “In any client code, if supertype object is substituted.
Polymorphism Liskov 8. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Data Abstraction SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
List Interface and Linked List Mrs. Furman March 25, 2010.
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.
Polymorphism SWE 619. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism Element.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
CSE 143 Lecture 12: Sets and Maps reading:
Collections Dwight Deugo Nesa Matic
Type Hierarchies. Type Hieararchy Why?: Want to define family of related types. At the top of the hierarchy, a type whose spec defines behavior common.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 5: Implementing Data Abstractions.
Java Collections Framework The client view. The Big Picture.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
Iterators.
CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs)
EECE 310: Software Engineering
Software Development Java Collections
Type Abstraction SWE Spring 2009.
Iteration Abstraction
slides adapted from Marty Stepp
Type Abstraction Liskov, Chapter 7.
Iteration Abstraction
SWE 619 Software Construction Last Modified, Fall 2015 Paul Ammann
Lecture 4: Data Abstraction CS201j: Engineering Software
Software Design Lecture : 39.
Type Abstraction SWE Spring 2013.
Presentation transcript:

Iteration Abstraction SWE Software Construction Fall 2009

2 Common Collections List (Interface) AbstractList ArrayList, Linked List, Vector Set (Interface) AbstractSet HashSet, TreeSet Map (Interface) AbstractMap HashMap, TreeMap Arrays Stack -subtype of Vector (Anomaly?)

3 Visiting each element of a collection Scenario: A common container has several objects stored Task: To visit each element in the container HOW?

4 Approaches IntSet choose() method? Remove – choose combination What is the problem here? Return the collection? Why is this bad? Return a clone? Is this better?

5 Approaches Custom built method? Close, but not it Problem? Not general We want uniformity Iteration Abstraction Client code is simplified, using is easy Implementation may be complex, but standard

6 Iterator Interface public Interface Iterator { public boolean hasNext(); public Object next() throws NoSuchElementException; public void remove() throws IllegalStateException; } Liskov has only first hasNext() and next() To satisfy the compiler, you need to override/implement remove() too

7 Specification public boolean hasNext() ; // Effects: Returns true if there are more elements to yield else returns false public Object next(); // Modifies: this // Effects: If there are more results to yield, returns the next result and modifies the state of this to record the yield. Otherwise, throws NoSuchElementEx.

8 Definitions An iterator is a procedure that returns a generator. A data abstraction can have one or more iterator methods, and there can also be standalone iterators. A generator is an object that produces the elements used in the iteration. The generator’s type is a subtype of Iterator. The specification of an iterator defines the behavior of the generator; a generator has no specification of its own. The iterator specification often includes a requires clause at the end constraining the code that uses the generator.

9 Examples: Poly and IntSet public Iterator terms() // Effects: Returns a generator that will produce exponents // of nonzero terms of this (as Integers) up to the degree, // in order of increasing exponent public Iterator elements() // Effects: Returns a generator that will produce all the elements // of this (as Integers) each exactly once, in arbitrary order // Requires: this must not be modified while the // generator is in use

10 Example: Poly Poly p … // p = x x 5 Iterator itr = p.iterator(); // Usual Iterator itr = p.terms(); // Liskov’s itr = [0,2,5] itr.hasNext()// return true, itr = [0,2,5] itr.next()// return 0, itr = [2,5] itr.next()// return 2, itr = [5] itr.hasNext()// return true, itr = [5] itr.next()// return 5, itr = [] itr.hasNext()// return false, itr = [] itr.next()// return NSEE, itr = []

11 Abstraction Function It’s the current list of things that you are going to send back Very close to a Stack top = next() element remove() adds complexity If multiple interfaces, iterator may not know about removed items! Only mutable data types are affected

12 Af(c) for Poly Iterator Poly p … // p = x x 5 AF(itr.hasNext())=[0,2,5]//true AF(itr.next())=[2,5]//0 AF(itr.next())=[5]//2 AF(itr.hasNext())=[5]//true AF(itr.next())=[]//5 AF(itr.hasNext())=[]//false AF(itr.next())=[] //NSEE

13 Implementation (Fig 6.8) public class Poly{ // Rep … public Iterator terms() {return new PolyGen(this);} // inner class private static class PolyGen implements Iterator { private Poly p; // the Poly being iterated private int n; // the next term to consider PolyGen (Poly it){ //Requires: it !=null p = it; if(p.trms[0] == 0) n=1; else n= 0; }

14 Implementation (contd.) public boolean hasNext() {return n<= p.deg;} public Object next () throws NSEE{ for(int e = n; e <= p.deg; e++) { if (p.trms[e] != 0) { n= e+1; return new Integer(e); } throw new NSEE(“Poly.terms”); } // end PolyGen }

15 Inner Class private class visibility only inside the class where defined no outside code can see/instantiate it if it has public methods && an instance available, outside code can call it

16 State for iterator How to figure out the state? Same way as AF(c) for Data Abstraction Ask yourself: What do I need to send back to the client? Example Rep state: [2,0,3,0,0,4] What if PolyGen was immutable?

17 Another example: PrimesGen private static class PrimesGen implements Iterator{ private Vector ps; // primes yielded private int p;// next candidate to try PrimesGen () { p =2 ; ps = new Vector();} //constructor public boolean hasNext() {return true;} // always true public Object next() throws NSEE { if (p==2) {p=3; return 2;} for (int n=p; true; n = n+2){ … //Prime number generation } }// end of PrimesGen

18 Abstract State for PrimesGen? Iterator itr = num.allPrimes(); AF(c) = [2,3,5,7,11,13,17,19, …] No end? Can we figure out the length of the tail? What does hasNext() have to do in this case? [2,3,5,7,9,…] Integer x = (Integer) itr.next(); [3,5,7,9,11,..] Integer y = (Integer) itr.next();[5,7,9,11,13,17,…].

19 Exercises What if there is an upper bound on the prime numbers? Suppose primes <100. What will be AF(c) be like? What will hasNext() implementation do? How will implementation of PrimesGen change?

20 Another Exercise public Interface TwoWayIterator { Object next (); Object previous (); boolean hasNext(); boolean hasPrevious(); Suppose we want to go back AND forward What does the abstraction function look like? Still a stack? What other state information is needed? How to implement this for Poly?

21 What about supporting remove()? The contract for remove(): Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method. This is complex! What is the new abstract state?

22 Iterable vs. Iterator Only one method required: public Iterator iterator(); Allows very nice code: // Note: that Collection implements Iterable // Side note: String does NOT implement Iterable Set mySet = new HashSet (); // populate mySet with various Strings for (String s : mySet) { // auto invocation of iterator(), next() // do something with s }