Chapter 28 Iterator Summary prepared by Kirk Scott 1.

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

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
CS0007: Introduction to Computer Programming
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.
1 Object-Oriented Programming (Java), Unit 20 Kirk Scott.
Unit 1: Java and Eclipse UML. Depending on the source, the acronym UML is said to stand for “unified modeling language” or “universal modeling language”.
Feb Ron McFadyen1 Iterator Pattern Recall Generic UML class diagram The iterator is used to access the elements of some aggregate. The aggregate.
Grouping Objects 3 Iterators, collections and the while loop.
Design Patterns in Java Appendix D UML at a Glance Summary prepared by Kirk Scott 1.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Grouping objects Collections and iterators. 04/11/2004Lecture 4: Grouping Objects2 Main concepts to be covered Collections Loops Iterators Arrays.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
A tour around Java General introduction to aspects of the language (these will be covered in more detail later) After this tour you should have a general.
CS0007: Introduction to Computer Programming Introduction to Arrays.
ArrayLists.  The Java API includes a class named ArrayList. The introduction to the ArrayList class in the Java API documentation is shown below.  java.lang.Object.
Java Unit 9: Arrays Declaring and Processing Arrays.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Design Patterns in Java Chapter 21 Template Method Summary prepared by Kirk Scott 1.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
Invitation to Computer Science, Java Version, Second Edition.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
4.1 Instance Variables, Constructors, and Methods.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Copyright © 2002, Systems and Computer Engineering, Carleton University Patterns.ppt * Object-Oriented Software Development Part 11.
Design Patterns in Java Chapter 1 Introduction Summary prepared by Kirk Scott 1.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
1 Object-Oriented Programming (Java), Unit 9 (comes before Unit 20) Kirk Scott.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 2.0.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Appendix D UML at a Glance Summary prepared by Kirk Scott 1.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 1.0.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
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’
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
Iterator Pattern. Traversing two different collections  When bringing two previously developed objects together, it can be difficult to change an implementation.
Grouping objects Arrays. 2 Fixed-size collections The maximum collection size may be pre-determined with an upper limit Array is an fixed-size collection.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Collections and Iteration Week 13.  Collections  ArrayList objects  Using loops with collections Collections and Iteration CONCEPTS COVERED THIS WEEK.
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.
Problem of the Day  Simplify this equation: (x - a) * (x - b) * (x - c) * … * (x - z)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Coming up ArrayList ArrayList vs Array – Declaration – Insertion – Access – Removal Wrapper classes Iterator object.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Summary prepared by Kirk Scott
Summary prepared by Kirk Scott
Summary prepared by Kirk Scott
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
JAVA COLLECTIONS LIBRARY
Summary prepared by Kirk Scott
CSE 143 Lecture 27: Advanced List Implementation
int [] scores = new int [10];
Java Programming Arrays
Collections and iterators
Collections and iterators
Presentation transcript:

Chapter 28 Iterator Summary prepared by Kirk Scott 1

An account of barley rations issued monthly to adults (30 or 40 pints) and children (20 pints) written in cuneiform on clay tablet, written in year 4 of King Urukagina (circa 2350 BC), from Girsu, Iraq, British Museum, LondonaccountcuneiformUrukagina GirsuBritish Museum 2

Cuneiform Tablet 3

iPadiPad (1st generation), a tablet computer 4

Design Patterns in Java Chapter 28 Iterator Summary prepared by Kirk Scott 5

The Introduction Before the Introduction The chapter in the book is divided into 3 parts: 1. Ordinary Iteration 2. Thread-Safe Iteration 3. Iterating over a Composite 6

This unit covers point 1 only Point 2, involving threads, is beyond the scope of this course Point 3, involving composites, is also beyond the scope of this course The Composite design pattern will be covered later in the course, but there is enough to worry about there without considering iteration 7

Book Definition of Pattern The intent of the Iterator pattern is to provide a way to access the elements of a collection sequentially. 8

Ordinary Iteration The initial block of overheads that follows is a repetition of something I show in CSCE 202 It goes through simple for each loops and while loops with iteration on the ArrayList class 9

Syntax Associated with the ArrayList Class (CSCE 202)

Importing the Class The ArrayList class has to be imported in order to be used in a program. import java.util.ArrayList;

Angle Bracket Notation to Specify Element Types In a program which uses a collection class, declarations with angle bracket notation specify what kinds of elements the collection contains. The following line of code would declare and construct an ArrayList containing references to Cup7 objects. ArrayList myCollection = new ArrayList ();

If it is desirable for the ArrayList to contain simple types like integers or doubles, the values should be stored in instances of the wrapper classes Integer and Double. ArrayList myCollection = new ArrayList (); 13

In For Each Loops Elements Cannot be Added to or Removed from a Collection Traversing all of the elements of an ArrayList can be done with a “for each” loop. In the for statement a local reference named someCup is declared. The for statement also contains a colon followed by the name of the collection to be accessed. The type of the local reference agrees with the type of the elements of the collection.

The loop runs through all of the elements of myCollection, successively assigning references of its elements to the local reference, someCup. The loop delivers access to successive elements of the collection, but it is not possible to call methods on the collection itself in the body of the loop. This means that it is not possible to add elements to, or remove them from the collection when using this syntax. 15

16 For each loop example: for(Cup7 someCup: myCollection) { myterminal.println(someCup); }

Iterators and Collections Traversing the elements of a collection is known as iteration. The Java collections framework includes interfaces named Iterator and Iterable. They support the traversal of a collection where it is possible to alter the collection while processing it.

The Iterable interface contains one method, named iterator(). Calling this method on a collection class returns a reference to an iterator. Angle bracket notation is used to specify what kinds of elements the iterator is dealing with. 18

If myCollection contains Cup7 elements, then the declaration of an iterator for the collection and the acquisition of a reference to it would take this form: Iterator myIterator = myCollection.iterator(); 19

Iterator Methods Three different methods can be called on an iterator. boolean hasNext() Returns true if the iteration has more elements.

E next() Returns the next element (of type E) in the iteration. Calling this method repeatedly until the hasNext() method returns false will return each element in the underlying collection exactly once. 21

void remove() Removes from the underlying collection the last element returned by the iterator. This method can be called only once per call to next(). Notice that it’s called on the iterator, not on the underlying collection. 22

In While Loops with Iterators, Elements can be Removed from a Collection Assume that myCollection contains references to the Cup7 class. These can be put in by a call to a simple add() method on the ArrayList. The iterator for the collection is obtained before the loop. The test for continuing to loop is a call to hasNext().

In the body of the loop, the call to next() returns a reference to the next element, and the call to remove() causes that element to be removed from the collection. Example code is given on the next overhead. This example removes from myCollection all elements which contain 0 or fewer seeds: 24

25 import java.util.Iterator; … Iterator myIterator = myCollection.iterator(); Cup7 someCup; while(myIterator.hasNext()) { someCup = myIterator.next(); if(someCup.getSeedCount() <= 0) myIterator.remove(); }

In For Loops with Iterators Elements can be Removed from a Collection The first part of the for statement obtains the iterator for the collection. The second part of the for statement causes the iteration to continue as long as there is another element in the collection See the code on the next overhead. Notice that there is a semicolon setting off a third part of the for statement, but the third part is not used.

import java.util.Iterator; … for(Iterator myIterator = myCollection.iterator(); myIterator.hasNext(); ) { if((myIterator.next().getSeedCount()) <= 0) myIterator.remove(); } 27

In Summary The system supplies an Iterator interface This class has three methods: hasNext(), next(), and remove() The system supplies an Iterable interface A class that implements this interface has an iterator() method that returns an instance of Iterator on an instance of that class 28

The point is that a Java collection class like ArrayList implements the Iterable interface Therefore it is possible to acquire an iterator for an instance of ArrayList This makes it possible do iteration over the ArrayList This holds true for any of the collection classes in the Java API 29

If you have already had the data structures and algorithms course, you may have created your own collection class (data structure with multiple elements) You may also already have been required to take the steps necessary to make your class implement the Iterable interface You may also have implemented a special case Iterator class 30

The example which will follow may or may not agree with the presentation given in any other course you have taken In any case, it illustrates applying the iterator idea to cups and seeds 31

A Cup and Seed Example of Iteration In this example the Cup class will extend the Java AbstractCollection class In other words, the cup class, a container for seeds, will become an official collection class where the contents it holds are instances of seeds In order to be a successful collection, the Cup class will have iterator(), size(), and add() methods 32

The existence of the iterator() method implies that it will be possible, within the Cup class, to construct an iterator for a cup This will require another class in the example: CupIterator This class will implement the Iterable interface That means it will implement the hasNext(), next(), and remove() methods 33

Example Code Example code will be given next The Seed class is given for reference, followed by the Cup class and the CupIterator class As usual, going through the code in minute detail may not be very useful 34

A couple of general observations can be made though: This implementation essentially relies on the underlying ArrayList that the cup contains in order to hold seeds Essentially, the methods needed in the Cup class are implemented by wrapping calls to corresponding ArrayList methods 35

The same is true of the CupIterator class It works with the ArrayList of seeds contained in the cup that it’s an iterator for If you go to the Web folder for this example, you will also find code that makes use of these classes That code will not be presented in these overheads The class code follows 36

import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Ellipse2D; import java.awt.geom.Point2D; import java.lang.*; import java.util.*; import java.io.*; public class Seed { private final Color seedColor = Color.BLUE; private final int diameter = 6; public Seed() { } 37

public int getDiameter() { return diameter; } public void drawSeed(Graphics2D g2, Point2D.Double locationPoint) { double xCoord = locationPoint.getX(); double yCoord = locationPoint.getY(); Ellipse2D.Double dot = new Ellipse2D.Double(xCoord, yCoord, diameter, diameter); g2.setColor(seedColor); g2.fill(dot); g2.setColor(Color.BLACK); } 38

import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Ellipse2D; import java.awt.geom.Point2D; import java.lang.*; import java.util.*; import java.io.*; /******* This declaration is correct. Because the Cup class extends a class that implements the Iterable interface, the Cup class is by definition iterable. *******/ public class Cup extends AbstractCollection { private Rectangle cupRectangle; private ArrayList seedList; public Cup(int seedCountIn, int cupX, int cupY, int cupW, int cupH) { cupRectangle = new Rectangle(cupX, cupY, cupW, cupH); seedList = new ArrayList (); for(int i = 0; i < seedCountIn; i++) { Seed aSeed = new Seed(); seedList.add(aSeed); } 39

public Cup(int cupX, int cupY, int cupW, int cupH) { cupRectangle = new Rectangle(cupX, cupY, cupW, cupH); seedList = new ArrayList (); } public Rectangle getRectangle() { return cupRectangle; } 40

public Point2D.Double generateSeedCoordinates(Seed aSeed) { double seedX = 0; double seedY = 0; Random generator = new Random(); if((aSeed.getDiameter() <= cupRectangle.getWidth()) && (aSeed.getDiameter() <= cupRectangle.getHeight())) { seedX = (int) cupRectangle.getX() + generator.nextInt((int) cupRectangle.getWidth() - aSeed.getDiameter()); seedY = (int) cupRectangle.getY() + generator.nextInt((int) cupRectangle.getHeight() - aSeed.getDiameter()); } else { seedX = cupRectangle.getX(); seedY = cupRectangle.getY(); } return new Point2D.Double(seedX, seedY); } 41

public ArrayList getCupArrayList() { return seedList; } public Iterator iterator() { return new CupIterator(this); } public int size() { return seedList.size(); } public boolean add(Seed seedIn) { return seedList.add(seedIn); } 42

import java.util.*; /******* This declaration is correct. It is the iterator class that implements the Iterator interface. The type of object that can be iterated over can be declared. *******/ public class CupIterator implements Iterator { ArrayList cupArrayList; int arrayListIndex; int state; public CupIterator(Cup cupIn) { cupArrayList = cupIn.getCupArrayList(); arrayListIndex = -1; state = -1; } public boolean hasNext() { try { //System.out.println("hasNext(), arrayListIndex test value: " + (arrayListIndex + 1)); cupArrayList.get(arrayListIndex + 1); return true; } catch(IndexOutOfBoundsException e) { return false; } 43

public Seed next() throws NoSuchElementException { if((arrayListIndex 0)) { arrayListIndex++; //System.out.println("next(), arrayListIndex value after incrementing: " + arrayListIndex); Seed seedRef = cupArrayList.get(arrayListIndex); state = 1; return seedRef; } else throw new NoSuchElementException(); } 44

public void remove() throws IllegalStateException { if(state == 1) { //System.out.println("remove(), arrayListIndex: " + arrayListIndex); cupArrayList.remove(arrayListIndex); arrayListIndex--; state = 0; } else throw new IllegalStateException(); } 45

Thread-Safe Iteration This is beyond the scope of this course No doubt it is a fascinating topic, full of tricks and traps, but if you don’t know what threads are, it’s pointless to talk about iteration in that context Even if you do know what threads are, it’s an advance topic It’s more useful to spend time covering other basic patterns than to go into this level of detail on this one 46

Iterating over a Composite This is the part of the chapter where the book develops some code, making the classes of the Composite design pattern implement the Iterable interface This means also developing a hierarchy of Iterator classes for components, leaves, and composites 47

Due to the organization of the course, the Composite design pattern will not be introduced until later Iterating over a composite is relatively complex and will not be pursued further— either now or later 48

Lasater’s UML for the Pattern Lasater’s UML diagram is given on the following overhead I find it a little hard to understand Could it be that the arrowheads are reversed? Shouldn’t the client have references to the Aggregate (Collection) and the Iterator, not the other way around? 49

50

UML for the Design Pattern Looking at Lasater’s UML diagram, it seemed that maybe the fundamental idea could be made clearer with a simpler picture My attempt is on the overhead following the next one The first thing I’m trying to indicate in the diagram is that a client has a reference to, or makes use of an instance of a Collection class 51

The client also makes use of the iterator on the collection, in a for each loop for example The collection may not have an iterator until the iterator() method is called on the collection in the client However, I indicate with the diamond that in some sense the collection has the iterator 52

53

Summary I won’t even bother to provide one… 54

The End 55