Iterator COMP 401, Spring 2013 Lecture 07 1/31/2013.

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

Why not just use Arrays? Java ArrayLists.
Singly linked lists Doubly linked lists
Linked Lists Linear collections.
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 Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Lecture # 21 Chapter 6 Uptill 6.4. Type System A type system is a collection of rules for assigning type expressions to the various parts of the program.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
12-Jul-15 Lists in Java Part of the Collections Framework.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Using arrays to create collections.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 22 Lists, Stacks, Queues, and Priority.
Arrays And ArrayLists - S. Kelly-Bootle
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Linked Lists. RHS – SOC 2 Linked lists We can already store collec- tions of objects in arrays and array lists – why would we need other data structures…?
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
(c) University of Washington14-1 CSC 143 Java Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Copyright © 2002, Systems and Computer Engineering, Carleton University Patterns.ppt * Object-Oriented Software Development Part 11.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
The Java Collections Framework By the end of this lecture you should be able to: use the ArrayList class to store a list of objects; use the HashSet class.
1 Iterators "First things first, but not necessarily in that order " -Dr. Who CS Computer Science II.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
CS261 – Data Structures Iterator ADT Dynamic Array and Linked List.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 13 Implementing.
CSC 212 – Data Structures Lecture 17: Stacks. Question of the Day Move one matchstick to produce a square.
Using Iterators Trey Chandler Burlington Williams High School Mr. Langner’s Class,
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
Ordered Linked Lists using Abstract Data Types (ADT) in Java Presented by: Andrew Aken.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
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’
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
CS 210 Iterator Pattern October 31 st, Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
What is Iterator Category: Behavioral Generic Way to Traverse Collection Not Related to Collection Implementation Details Not Related to the direction/fashion.
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.
Using Sequential Containers Lecture 8 Hartmut Kaiser
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.
Collections Dwight Deugo Nesa Matic
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
(c) University of Washington20c-1 CSC 143 Binary Search Trees.
Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
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.
Software Development Iterators
08/15/09 Design Patterns James Brucker.
"First things first, but not necessarily in that order." -Dr. Who
Interator and Iterable
"First things first, but not necessarily in that order " -Dr. Who
CSC 143 Binary Search Trees.
Software Design Lecture : 39.
Part of the Collections Framework
A type is a collection of values
Presentation transcript:

Iterator COMP 401, Spring 2013 Lecture 07 1/31/2013

Design Situation Suppose we have an object that encapsulates some sort of collection. – SongLibrary A collection of songs in an iTunes-like system – PolygonModel A collection of polygons in a 3D modeling system – Polygon A collection of points in our Assignment 2

Design Situation Now suppose we have code outside of this collection object that needs to examine each element of the underlying collection in turn. – SongFilter A object that represents a set of search criteria that is to be applied to a collection of songs – An intersection test in which each polygon of a PolygonModel needs to be evaluated

Strategy 1: Provide access to underlying collection as an array. SongLibrary – public Song[] getSongs() PolygonModel – public Polygon[] getPolygons() Drawbacks? – May have to do a lot of work to create the array – Collection may be result of generative process

Strategy 2: Provide index access to each underlying item in collection SongLibrary – public int getNumSongs(); – public Song getSong(int song_idx); PolygonModel – public int getNumPolygons(); – public Polygon getPolygon(int polygon_idx); Drawbacks? – Doesn’t help with generative collections – Imposes restrictions on how collection is represented and linearized – Deteriorates encapsulation

Strategy 3: Internalize a “cursor” SongLibrary – public void resetSongCursor(); – public Song getNextSong(); – public boolean isCursorAtEnd(); Drawbacks? – Can’t have two traversals going at the same time. – But, this does come close.

Iterator Design Pattern “Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation” – Gang of Four, Design Patterns Consider: for(int i=0; i<slist.size(); i++) { Song next_song = slist.get(i); // Do something with next_song. }

Iterator Design Pattern Iterator object encapsulates details of item traversal. – Understands details of the underlying collection. – Manages order of items May want a traversal that is not just first to last. Underlying collection may not be linear. – Manages state of traversal Allows traversal to be picked up again later. Assumption: underlying collection is not changed or modified while the traversal is occurring. – Interator should be able to detect this and signal an error – Variant of pattern will have iterator provide methods that modify underlying collection safely

Elements of Iterator Pattern Collection object is “iterable” – Provides a method that returns an object that acts as an iterator. Iterator object provides access to the elements in turn. – A method to test whether more items exist. – A method to retrieve the next item.

Java Iterator Pattern Interfaces The Java Collections Framework defines two generic interfaces for supporting the interable design pattern – Implemented by the various collection types such as List, Map, Set, etc. Iterable – Interator iterator() Iterator

boolean hasNext() – Are we at the end of the traversal? E next() – Get the next item of the traversal. – Throws a runtime exception if no next item. void remove() – Not supported by all implementations. – Safely removes last item retrieved by next() from the underlying collection.

Iterable examples lec7.v1 – Main1 Simple use – Main2 Parallel iterators – Main3 Simultaneous iterators – Main4 for – each syntactic sugar

Main1 Visualized (1) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy

Main1 Visualized (2) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy Iterator iter 0 0 next_idx list

Main1 Visualized (3) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy Iterator iter 0 0 next_idx list public boolean hasNext() { if (next_idx < list.size()) { return true; } return false; } NOTE: This may or may not be how it is actually implemented, but it is effectively what is going on.

Main1 Visualized (4) ArrayList<Song> slistArrayList<Song> slist 0 Words and Guitar Dig Me Out Jenny Little Babies Buy Her Candy Iterator iter 1 1 next_idx list public Song next() { Song s = list.get(next_idx); next_idx++; return s; } NOTE: Real implementation would first check to see if hasNext() is still true and throw an exception otherwise.

lec7.v1.Main2 Parallel iteration – Processes two different lists Iterator associated with each. Iterators advance unevenly

lec7.v1.Main3 Simultaneous iteration – 2 Iterators, 1 List Insert your own joke here.

lec7.v1.Main4 Java provides “syntactic sugar” for common use of iterators. – Supposing e_coll is Iterable, then these are equivalent: Iterator iter = e_coll.iterator(); while (iter.hasNext()) { E elem = iter.next(); // Do something with element } for (E elem : e_coll) { // Do something with elem }

lec7.v2 A more complicated iterator – Can build iterators that do things other than just go through every item. Prior examples made use of Iterator built into List, here we are going to implement our own specialized version of Iterator