Iterators. Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.



Similar documents
A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Iterator Pattern. CSIE Department, NTUT Chien-Hung Liu. Provide a way to access the elements of an aggregate object sequentially

Ordered Lists and Binary Trees

Data Structures and Algorithms Lists

DATA STRUCTURES USING C

Data Structures and Algorithms

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

JAVA COLLECTIONS FRAMEWORK

Data Structures and Algorithms

Optimal Binary Search Trees Meet Object Oriented Programming

Chapter 8: Bags and Sets

What Is Recursion? Recursion. Binary search example postponed to end of lecture

Binary Search Trees (BST)

CMSC 132: Object-Oriented Programming II. Design Patterns I. Department of Computer Science University of Maryland, College Park

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Circular Linked List. Algorithms and Data Structures

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Heaps & Priority Queues in the C++ STL 2-3 Trees

Structural Design Patterns Used in Data Structures Implementation

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Recursive Implementation of Recursive Data Structures

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Data Structure with C

Class 32: The Java Collections Framework

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Common Data Structures

Section IV.1: Recursive Algorithms and Recursion Trees

Algorithms and Data Structures Written Exam Proposed SOLUTION

recursion, O(n), linked lists 6/14

10CS35: Data Structures Using C

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

CMSC 202H. ArrayList, Multidimensional Arrays

Data Structures. Level 6 C Module Descriptor

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Stacks. Data Structures and Data Types. Collections

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Binary Search Trees CMPSC 122

Lecture Notes on Binary Search Trees

Data Structures and Algorithms Written Examination

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

The Smalltalk Programming Language. Beatrice Åkerblom

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Analysis of a Search Algorithm

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Optimizing Generation of Object Graphs in Java PathFinder

COMPUTER SCIENCE. Paper 1 (THEORY)

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION /5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

Computing Concepts with Java Essentials

Stack Allocation. Run-Time Data Structures. Static Structures

Symbol Tables. Introduction

Stacks. Linear data structures

Efficient Data Structures for Decision Diagrams

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Lecture 12 Doubly Linked Lists (with Recursion)

Node-Based Structures Linked Lists: Implementation

Data Structures, Practice Homework 3, with Solutions (not to be handed in)

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Object Oriented Databases. OOAD Fall 2012 Arjun Gopalakrishna Bhavya Udayashankar

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)

Chapter 13: Query Processing. Basic Steps in Query Processing

Persistent Binary Search Trees

Binary Search Trees. A Generic Tree. Binary Trees. Nodes in a binary search tree ( B-S-T) are of the form. P parent. Key. Satellite data L R

Software Engineering Techniques

Lecture Notes on Binary Search Trees

Introduction to data structures

public static void main(string[] args) { System.out.println("hello, world"); } }

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

Programming Languages

Habanero Extreme Scale Software Research Project

Parameter Passing in Pascal

Binary Heap Algorithms

Algorithms and Data Structures

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

C++ INTERVIEW QUESTIONS

ProfBuilder: A Package for Rapidly Building Java Execution Profilers Brian F. Cooper, Han B. Lee, and Benjamin G. Zorn

Java Interview Questions and Answers

CmpSci 187: Programming with Data Structures Spring 2015

Lecture Notes on Linear Search

PES Institute of Technology-BSC QUESTION BANK

LINKED DATA STRUCTURES

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Instance Creation. Chapter

D06 PROGRAMMING with JAVA

Lecture 10: Dynamic Memory Allocation 1: Into the jaws of malloc()

Introduction to Object-Oriented Programming

Chapter 14 The Binary Search Tree

Advanced OOP Concepts in Java

Abstraction and Abstract Data Types

Fast Sequential Summation Algorithms Using Augmented Data Structures

Data Types. Abstract Data Types. ADTs as Design Tool. Abstract Data Types. Integer ADT. Principle of Abstraction

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

Transcription:

Iterators Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation when to use it - to access an aggregate object's contents without exposing its internal representation. - to support multiple traversals of aggregate objects. - to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration). Java Example Enumeration, Iterator, and Streams in Java are iterators Vector listofstudents = new Vector(); Iterator list = listofstudents.iterator(); while ( list.hasnext() ) Student x = list.next(); System.out.println( x ); C# Example Student[ ] listofstudent; foreach (Student x in listofstudent ) Console.WriteLine(x.ToString()); Smalltalk Examples Streams, do:, select:, reject:, collect:, detect:, inject:into: are iterators in Smalltalk sum sum := 0. #( 1 7 2 3 9 3 50) do: [:each sum := sum + each squared]. ^sum #( 1 7 2 3 9 3 50) inject: 0 into: [:partialsum :number partialsum + number squared] 'this is an example' select: [:each each isvowel ]

What's The Big Deal? void print(arraylist list) for( int k = 0; k < list.size(); k++ ) System.out.println( list.get(k) ); void print(linkedlist list ) Node current = list.first(); System.out.println( current ); while (current.hasnext() ) current = current.next(); System.out.println( current ); void print(collection list ) Iterator items = list.iterator(); while (items.hasnext() ) System.out.println( items.next() ); print: acollection acollection do: [:each Transcript show: each; cr] What's The Big Deal? Iterator abstracts out underlying representation of collection Programmer does not have to know implementation details of each type of collection Can write code that works for wide range of collects Do not have to change code if change the type of collection used Java Iterators & Arrays? Arrays are common collections How can one get an iterator on a Java array? How would you pass an array to the following function? void print(collection list ) Iterator items = list.iterator(); while (items.hasnext() ) System.out.println( items.next() ); Sample Implementation of Java Enumerator class VectorIterator implements Enumeration Vector iteratee; int count;

VectorIterator(Vector v) iteratee = v; count = 0; public boolean hasmoreelements() return count < iteratee.elementcount; public Object nextelement() synchronized (iteratee) if (count < iteratee.elementcount) return iteratee.elementdata[count++]; throw new NoSuchElementException("VectorIterator"); The iterator is using privileged access to Vectors fields Issues Concrete vs. Polymorphic Iterators Concrete Use Explicit Iterator Type Reader iterator = new StringReader( "cat"); int c; while (-1!= (c = iterator.read() )) System.out.println( (char) c); Polymorphic Actual type of iterator is not known Vector listofstudents = new Vector(); Iterator list = listofstudents.iterator(); while ( list.hasnext() ) Console.println( list.next() ); Polymorphic iterators can cause problems with memory leaks in C++ because they are on the heap! Who Controls the iteration? External (Active) Vector listofstudents = new Vector(); Iterator list = listofstudents.iterator(); while ( list.hasnext() ) Console.println( list.next() ); Iteration control code is repeated for each use of the iterator Who Controls the iteration?

Internal (Passive) 'this is an example' select: [:each each isvowel ] Control code is inside the iterator Programmer Does not repeat control code Can focus on what to do not how to do it Who Defines the Traversal Algorithm? Object being Iterated Iterator can store where we are In a Vector this could mean the index of the current item In a tree structure it could mean a pointer to current node and stack of past nodes BinaryTree searchtree = new BinaryTree(); // code to add items not shown Iterator asearch = searchtree.getiterator(); Iterator bsearch = searchtree.getiterator(); Object first = searchtree.nextelement( asearch ); Object stillfirst = searchtree.nextelement( bsearch ); (internal) Iterator Makes it easier to have multiple iterator algorithms on same type On Vector class, why not have a reverseiterator which goes backwards? In a complex structure the iterator may need access to the iteratee's implementation How Robust is the iterator? What happens when items are added/removed from the iteratee while an iterator exists? Vector listofstudents = new Vector(); Enumeration list = listofstudents.elements(); Iterator failfastlist = listofstudents.iterator(); listofstudents.add( new Student( "Roger") ); list.hasmoreelements(); failfastlist.hasnext(); //Exception thrown here Additional Iterator Operations Augmenting basic iteration operations may improve their usefulness previous() back up one location

add( Object item) add item to the iteratee at current location remove() remove the current item from the iteratee skipto( some location, item or condition ) go to the location indicated mark() mark current location for future return Iterators and Privileged Access An iterator may need privileged access to the aggregate structure for traversal Iterators for Composites Traversing a complex structure like a graph, tree, or composite can be difficult An internal iterator can use recursion to keep track of where to go next For example using a depth-first search algorithm on graph If each element in the aggregate knows how to traverse to the next element and previous element, than an external iterator can be used Null Iterator A Null iterator for the empty aggregates can be useful of each. NullObject Structure NullObject implements all the operations of the real object, These operations do nothing or the correct thing for nothing

Binary Search Tree Example Without Null Object public class BinaryNode Node left = new NullNode(); Node right = new NullNode(); int key; public boolean includes( int value ) if (key == value) return true; else if ((value < key) & left == null) ) return false; else if (value < key) return left.includes( value ); else if (right == null) return false; else return right.includes(value); etc. Binary Search Tree ExampleClass Structure Object Structure Searching for a Key public class BinaryNode extends Node Node left = new NullNode(); Node right = new NullNode(); int key; public boolean includes( int value ) if (key == value) return true; else if (value < key ) return left.includes( value ); else return right.includes(value); etc.

public class NullNode extends Node public boolean includes( int value ) return false; etc. Comments on Example BinaryNode always has two subtrees No need check if left, right are null Since NullNode has no state just need one instance Use singleton pattern for the one instance Access to NullNode is usually restricted to BinaryNode Forces indicate that one may not want to use the Null Object pattern However, familiarity with trees makes it easy to explain the pattern Implementing an add method in NullNode Requires reference to parent or Use proxy Refactoring Introduce Null Object [3] You have repeated checks for a null value Replace the null value with a null object Example customer isnil iftrue: [plan := BillingPlan basic] iffalse: [plan := customer plan] becomes: Create NullCustomer subclass of Customer with: NullCustomer>>plan ^BillingPlan basic Make sure that each customer variable has either a real customer or a NullCustomer Now the code is: plan := customer plan Often one makes a Null Object a singleton

Applicability Use the Null Object pattern when: Some collaborator instances should do nothing You want clients to ignore the difference between a collaborator that does something and one that does nothing Client does not have to explicitly check for null or some other special value You want to be able to reuse the do-nothing behavior so that various clients that need this behavior will consistently work in the same way Use a variable containing null or some other special value instead of the Null Object pattern when: Very little code actually uses the variable directly The code that does use the variable is well encapsulated - at least in one class The code that uses the variable can easily decide how to handle the null case and will always handle it the same way Consequences Advantages Uses polymorphic classes Simplifies client code Encapsulates do nothing behavior Makes do nothing behavior reusable Disadvantages Forces encapsulation Makes it difficult to distribute or mix into the behavior of several collaborating objects May cause class explosion Forces uniformity Different clients may have different idea of what do nothing means Is non-mutable NullObject objects cannot transform themselves into a RealObject become: message in Smalltalk allows null objects to transform themselves into real objects

Implementation Too Many classes Eliminate one class by making NullObject a subclass of RealObject Multiple Do-nothing meanings If different clients expect do nothing to mean different things use Adapter pattern to provide different donothing behavior to NullObject Transformation to RealObject In some cases a message to NullObject should transform it to a real object Use the proxy pattern Generalized Null Object Pattern A generalized Null Object pattern based on Objective-C with an implementation in Smalltalk can be found at: http://www.smalltalkchronicles.net/edition2-1/null_object_pattern.htm Copyright, All rights reserved. 2005 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA. OpenContent license defines the copyright on this document.