Iterator Pattern. Traversing two different collections  When bringing two previously developed objects together, it can be difficult to change an implementation.

Slides:



Advertisements
Similar presentations
Java Programming: Advanced Topics 1 Collections and Utilities.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
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++)
Feb Ron McFadyen1 Iterator Pattern Recall Generic UML class diagram The iterator is used to access the elements of some aggregate. The aggregate.
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.
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
15-Jun-15 Lists in Java Part of the Collections Framework.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Feb Ron McFadyen1 Iterator Pattern Generic UML class diagram The iterator is used to access the elements of some aggregate. The aggregate interface.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
CS 280 Data Structures Professor John Peterson. Project 9 Questions? IS280.
1 Collections Working with More than One Number or Data Type or Object.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
CS2110: SW Development Methods
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities Chapter 4.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
(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.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
Chapter 9: The Iterator Pattern
程式語言結構 Final Project. Goal The student can gain the knowledge of the object operation for the Java programming language. –Class –Interface.
LinkedList Many slides from Horstmann modified by Dr V.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
程式語言結構 Final Project 老師: Gwan-Hwan Hwang. Goal The students can gain the knowledge of the object operation for the Java programming language. –Class –Interface.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
(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.
Computer Science 209 Software Development Inheritance and Composition.
CS 210 Iterator Pattern October 31 st, Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another.
What is Iterator Category: Behavioral Generic Way to Traverse Collection Not Related to Collection Implementation Details Not Related to the direction/fashion.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Iteration Abstraction SWE Software Construction Fall 2009.
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.
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.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
Iterators.
Software Development Iterators
University of Central Florida COP 3330 Object Oriented Programming
Implementing ArrayList Part 1
Iterator Design Pattern
ArraySet Methods and ArrayIterator
Menu item at a restaurant
CS2110: Software Development Methods
Introduction to Collections
Software Design Lecture : 39.
TCSS 143, Autumn 2004 Lecture Notes
Part of the Collections Framework
Presentation transcript:

Iterator Pattern

Traversing two different collections  When bringing two previously developed objects together, it can be difficult to change an implementation  Diner merger with PancakeHouse  Menu items -- same for both collections -- this is key  When bringing two previously developed objects together, it can be difficult to change an implementation  Diner merger with PancakeHouse  Menu items -- same for both collections -- this is key

public class DinerMenu implements Menu { static final int MAX_ITEMS = 6; int numberOfItems = 0; MenuItem[] menuItems; public DinerMenu() { menuItems = new MenuItem[MAX_ITEMS]; addItem("Steamed Veggies and Brown Rice", "Steamed vegetables over brown rice", true, 3.99); addItem(…) } public void addItem(String name, String description, boolean vegetarian, double price) { MenuItem menuItem = new MenuItem(name, description, vegetarian, price); if (numberOfItems >= MAX_ITEMS) { System.err.println("Sorry, menu is full! Can't add item to menu"); } else { menuItems[numberOfItems] = menuItem; numberOfItems = numberOfItems + 1; } public MenuItem[] getMenuItems() { return menuItems; } // other menu methods here } public class DinerMenu implements Menu { static final int MAX_ITEMS = 6; int numberOfItems = 0; MenuItem[] menuItems; public DinerMenu() { menuItems = new MenuItem[MAX_ITEMS]; addItem("Steamed Veggies and Brown Rice", "Steamed vegetables over brown rice", true, 3.99); addItem(…) } public void addItem(String name, String description, boolean vegetarian, double price) { MenuItem menuItem = new MenuItem(name, description, vegetarian, price); if (numberOfItems >= MAX_ITEMS) { System.err.println("Sorry, menu is full! Can't add item to menu"); } else { menuItems[numberOfItems] = menuItem; numberOfItems = numberOfItems + 1; } public MenuItem[] getMenuItems() { return menuItems; } // other menu methods here }

public class PancakeHouseMenu implements Menu { ArrayList menuItems; public PancakeHouseMenu() { menuItems = new ArrayList(); addItem("K&B's Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true, 2.99); … } public void addItem(String name, String description, boolean vegetarian, double price) { MenuItem menuItem = new MenuItem(name, description, vegetarian, price); menuItems.add(menuItem); } public ArrayList getMenuItems() { return menuItems; } // other menu methods here } public class PancakeHouseMenu implements Menu { ArrayList menuItems; public PancakeHouseMenu() { menuItems = new ArrayList(); addItem("K&B's Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true, 2.99); … } public void addItem(String name, String description, boolean vegetarian, double price) { MenuItem menuItem = new MenuItem(name, description, vegetarian, price); menuItems.add(menuItem); } public ArrayList getMenuItems() { return menuItems; } // other menu methods here }

public class Waitress { PancakeHouseMenu pancakeHouseMenu; ArrayList breakfastItems; DinerMenu dinerMenu; MenuItems[] lunchItems; public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu) { this.pancakeHouseMenu = pancakeHouseMenu; breakfastItems = pancakeHouseMenu.getMenuItems(); this.dinerMenu = dinerMenu; lunchItems = dinerMenu.getMenuItems(); } public void printMenu(){ for (int i = 0; breakfastItems.size(); i++) { MenuItem menuItem = (MenuItem)breakfastItems.get(i); System.out.println(menuItem.getName()+” “+menuItem.getPrice()); System.out.println(menuItem.getDescription()); } for (int i = 0; lunchItems.length; i++) { MenuItem menuItem = lunchItems[i]; System.out.println(menuItem.getName()+” “+menuItem.getPrice()); System.out.println(menuItem.getDescription()); } public class Waitress { PancakeHouseMenu pancakeHouseMenu; ArrayList breakfastItems; DinerMenu dinerMenu; MenuItems[] lunchItems; public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu) { this.pancakeHouseMenu = pancakeHouseMenu; breakfastItems = pancakeHouseMenu.getMenuItems(); this.dinerMenu = dinerMenu; lunchItems = dinerMenu.getMenuItems(); } public void printMenu(){ for (int i = 0; breakfastItems.size(); i++) { MenuItem menuItem = (MenuItem)breakfastItems.get(i); System.out.println(menuItem.getName()+” “+menuItem.getPrice()); System.out.println(menuItem.getDescription()); } for (int i = 0; lunchItems.length; i++) { MenuItem menuItem = lunchItems[i]; System.out.println(menuItem.getName()+” “+menuItem.getPrice()); System.out.println(menuItem.getDescription()); }

Waitress code  Need two loops to go through the two collections  Will need to add another loop if we add another collection later  waitress has to know intimate details of the collection code -- bad form!  Need two loops to go through the two collections  Will need to add another loop if we add another collection later  waitress has to know intimate details of the collection code -- bad form!

Let’s Encapsulate!  We can encapsulate the iteration to avoid sharing too much information

Iterator Interface public interface Iterator { boolean hasNext(); Object next(); } public interface Iterator { boolean hasNext(); Object next(); }

public class DinerMenuIterator implements Iterator { MenuItem[] items; int position = 0; public DinerMenuIterator(MenuItem[] items) { this.items = items; } public Object next() { MenuItem menuItem = items[position]; position = position + 1; return menuItem; } public boolean hasNext() { if (position >= items.length || items[position] == null) { return false; } else { return true; } public class DinerMenuIterator implements Iterator { MenuItem[] items; int position = 0; public DinerMenuIterator(MenuItem[] items) { this.items = items; } public Object next() { MenuItem menuItem = items[position]; position = position + 1; return menuItem; } public boolean hasNext() { if (position >= items.length || items[position] == null) { return false; } else { return true; }

public class DinerMenu implements Menu { static final int MAX_ITEMS = 6; int numberOfItems = 0; MenuItem[] menuItems; //constructor here //addItem here /* don’t need getMenuItems now that we have an Iterator! public MenuItem[] getMenuItems() { return menuItems; }*/ public Iterator createIterator() { return new DinerMenuIterator(menuItems); } // other menu methods here } public class DinerMenu implements Menu { static final int MAX_ITEMS = 6; int numberOfItems = 0; MenuItem[] menuItems; //constructor here //addItem here /* don’t need getMenuItems now that we have an Iterator! public MenuItem[] getMenuItems() { return menuItems; }*/ public Iterator createIterator() { return new DinerMenuIterator(menuItems); } // other menu methods here }

New Waitress Code

public class Waitress { PancakeHouseMenu pancakeHouseMenu; DinerMenu dinerMenu; public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu) { this.pancakeHouseMenu = pancakeHouseMenu; this.dinerMenu = dinerMenu; } public void printMenu() { Iterator pancakeIterator = pancakeHouseMenu.createIterator(); Iterator dinerIterator = dinerMenu.createIterator(); System.out.println("MENU\n----\nBREAKFAST"); printMenu(pancakeIterator); System.out.println("\nLUNCH"); printMenu(dinerIterator); } private void printMenu(Iterator iterator) { while (iterator.hasNext()) { MenuItem menuItem = (MenuItem)iterator.next(); System.out.print(menuItem.getName() + ", "); System.out.print(menuItem.getPrice() + " -- "); System.out.println(menuItem.getDescription()); } //other methods } public class Waitress { PancakeHouseMenu pancakeHouseMenu; DinerMenu dinerMenu; public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu) { this.pancakeHouseMenu = pancakeHouseMenu; this.dinerMenu = dinerMenu; } public void printMenu() { Iterator pancakeIterator = pancakeHouseMenu.createIterator(); Iterator dinerIterator = dinerMenu.createIterator(); System.out.println("MENU\n----\nBREAKFAST"); printMenu(pancakeIterator); System.out.println("\nLUNCH"); printMenu(dinerIterator); } private void printMenu(Iterator iterator) { while (iterator.hasNext()) { MenuItem menuItem = (MenuItem)iterator.next(); System.out.print(menuItem.getName() + ", "); System.out.print(menuItem.getPrice() + " -- "); System.out.println(menuItem.getDescription()); } //other methods }

Compare and contrast Waitresses Oldnew Waitress must know about menu implementation Menus are encapsulated Needs 2 loopsNeed 1 loop Waitress bound to concrete classes (MenuItem[] and ArrayList) Waitress now uses an interface (Iterator)

Java.util.iterator  Now that we’ve built an iterator from scratch, we can learn about Java’s Iterator interface  hasNext()  Next()  remove()  Optional -- in unsupported must throw  Java.lang.unsupportedOperationExc eption  Now that we’ve built an iterator from scratch, we can learn about Java’s Iterator interface  hasNext()  Next()  remove()  Optional -- in unsupported must throw  Java.lang.unsupportedOperationExc eption

Updating menus

import java.util.ArrayList; import java.util.Iterator; public class PancakeHouseMenu implements Menu { ArrayList menuItems; //constructor here public Iterator createIterator() { return menuItems.iterator(); } // other menu methods here } ArrayList already implements the Iterator interface import java.util.ArrayList; import java.util.Iterator; public class PancakeHouseMenu implements Menu { ArrayList menuItems; //constructor here public Iterator createIterator() { return menuItems.iterator(); } // other menu methods here } ArrayList already implements the Iterator interface

import java.util.Iterator; public class DinerMenuIterator implements Iterator { MenuItem[] list; int position = 0; public DinerMenuIterator(MenuItem[] list) {//constructor here } public Object next() { //current implemenation } public boolean hasNext() { //current implementation } public void remove() { if (position <= 0) { throw new IllegalStateException ("You can't remove an item until you've done at least one next()"); } if (list[position-1] != null) { for (int i = position-1; i < (list.length-1); i++) { list[i] = list[i+1]; } list[list.length-1] = null; } import java.util.Iterator; public class DinerMenuIterator implements Iterator { MenuItem[] list; int position = 0; public DinerMenuIterator(MenuItem[] list) {//constructor here } public Object next() { //current implemenation } public boolean hasNext() { //current implementation } public void remove() { if (position <= 0) { throw new IllegalStateException ("You can't remove an item until you've done at least one next()"); } if (list[position-1] != null) { for (int i = position-1; i < (list.length-1); i++) { list[i] = list[i+1]; } list[list.length-1] = null; }

Updating waitress with menu interface public interface Menu{ public Iterator createIterator(); } Add “implements Menu” to DinerMenu and PancakeHouseMenu Then… public interface Menu{ public Iterator createIterator(); } Add “implements Menu” to DinerMenu and PancakeHouseMenu Then…

import java.util.Iterator; public class Waitress { Menu pancakeHouseMenu; Menu dinerMenu; public Waitress(Menu pancakeHouseMenu, Menu dinerMenu) { this.pancakeHouseMenu = pancakeHouseMenu; this.dinerMenu = dinerMenu; } public void printMenu() { Iterator pancakeIterator = pancakeHouseMenu.createIterator(); Iterator dinerIterator = dinerMenu.createIterator(); System.out.println("MENU\n----\nBREAKFAST"); printMenu(pancakeIterator); System.out.println("\nLUNCH"); printMenu(dinerIterator); } private void printMenu(Iterator iterator) { while (iterator.hasNext()) { MenuItem menuItem = (MenuItem)iterator.next(); System.out.print(menuItem.getName()+", ”+menuItem.getPrice()+ " -- "); System.out.println(menuItem.getDescription()); } //other methods } import java.util.Iterator; public class Waitress { Menu pancakeHouseMenu; Menu dinerMenu; public Waitress(Menu pancakeHouseMenu, Menu dinerMenu) { this.pancakeHouseMenu = pancakeHouseMenu; this.dinerMenu = dinerMenu; } public void printMenu() { Iterator pancakeIterator = pancakeHouseMenu.createIterator(); Iterator dinerIterator = dinerMenu.createIterator(); System.out.println("MENU\n----\nBREAKFAST"); printMenu(pancakeIterator); System.out.println("\nLUNCH"); printMenu(dinerIterator); } private void printMenu(Iterator iterator) { while (iterator.hasNext()) { MenuItem menuItem = (MenuItem)iterator.next(); System.out.print(menuItem.getName()+", ”+menuItem.getPrice()+ " -- "); System.out.println(menuItem.getDescription()); } //other methods }

definitions  The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.  Aggregate object - an object that is a collection of other objects of the same type, intended primarily for storage  The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.  Aggregate object - an object that is a collection of other objects of the same type, intended primarily for storage

> Aggregate createIterator() Client > Iterator hasNext() next() remove() ConcreteAggregate createIterator() ConcreteIterator createIterator()

Iterator faq  Backwards iteration  Yes, but you need to add some methods. Which?  Java also has ListIterator, similar  Ordering  Iterator does not imply ordering  Backwards iteration  Yes, but you need to add some methods. Which?  Java also has ListIterator, similar  Ordering  Iterator does not imply ordering

Design Principle sinlge responsibility  A class should have only one reason to change  An aggregate that manages its own collection AND iteration has two opportunities to change.  Where?  A class should have only one reason to change  An aggregate that manages its own collection AND iteration has two opportunities to change.  Where?

Cohesion  A measure of how closely a class supports a single purpose or responsibility  High cohesion:designed around a set of related functions  Low cohesion: designed around unrelated functions  A measure of how closely a class supports a single purpose or responsibility  High cohesion:designed around a set of related functions  Low cohesion: designed around unrelated functions

Cohesion examples  Book pg. 340

Iterator and Hashtable  Hash table accesses Iterator indirectly

import java.util.*; public class CafeMenu implements Menu { Hashtable menuItems = new Hashtable(); public CafeMenu() { //constructor code here } public void addItem(String name, String description, boolean vegetarian, double price) { MenuItem menuItem = new MenuItem(name, description, vegetarian, price); menuItems.put(menuItem.getName(), menuItem); } public Iterator createIterator() { return menuItems.values().iterator(); } import java.util.*; public class CafeMenu implements Menu { Hashtable menuItems = new Hashtable(); public CafeMenu() { //constructor code here } public void addItem(String name, String description, boolean vegetarian, double price) { MenuItem menuItem = new MenuItem(name, description, vegetarian, price); menuItems.put(menuItem.getName(), menuItem); } public Iterator createIterator() { return menuItems.values().iterator(); }

Iterators and Collections  Java Colleections Framework  Vector, LinkedLIST, Stack, etc.  Java.util.collection interface  Each collection object knows how to create its own iterator! Sweet!  Java Colleections Framework  Vector, LinkedLIST, Stack, etc.  Java.util.collection interface  Each collection object knows how to create its own iterator! Sweet!

> Collection add() addAll() clear() contains() containsAll() equals() hashCode() isEmpty() iterator() remove() removeAll() reatainAll() size() toArray()

For/in is the new for  With java5 we have a new syntax for iterating over collections  For(Object obj: collection)  No need to get the iterator  Generics  Type security  With java5 we have a new syntax for iterating over collections  For(Object obj: collection)  No need to get the iterator  Generics  Type security

Composite  Iterator is related to the Composite Pattern  We are not going to cover it this semester, but you can read about it in your book.  Iterator is related to the Composite Pattern  We are not going to cover it this semester, but you can read about it in your book.