Top Banner
Chapter 28 Iterator Summary prepared by Kirk Scott 1
55

Chapter 28 Iterator Summary prepared by Kirk Scott 1.

Dec 29, 2015

Download

Documents

Charlene Rice
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

1

Chapter 28Iterator

Summary prepared by Kirk Scott

Page 2: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

2

• 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, London

Page 3: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

3

Cuneiform Tablet

Page 4: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

4

iPad (1st generation), a tablet computer

Page 5: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

5

Design Patterns in JavaChapter 28

Iterator

Summary prepared by Kirk Scott

Page 6: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

6

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

Page 7: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

7

• 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

Page 8: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

8

Book Definition of Pattern

• The intent of the Iterator pattern is to provide a way to access the elements of a collection sequentially.

Page 9: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

9

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

Page 10: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

10

9.5 Syntax Associated with the ArrayList Class (CSCE 202)

Page 11: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

11

9.5.1 Importing the Class

• The ArrayList class has to be imported in order to be used in a program.

• import java.util.ArrayList;

Page 12: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

12

9.5.2 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<Cup7> myCollection = new ArrayList<Cup7>();

Page 13: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

• 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<Double> myCollection = new ArrayList<Double>();

13

Page 14: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

14

9.5.3 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.

Page 15: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

• 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

Page 16: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

16

For each loop example:

• for(Cup7 someCup: myCollection)• {• myterminal.println(someCup);• }

Page 17: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

17

9.5.4 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.

Page 18: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

• 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

Page 19: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

• 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<Cup7> myIterator = myCollection.iterator();

19

Page 20: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

20

9.5.5 Iterator Methods

• Three different methods can be called on an iterator.

• boolean hasNext()• Returns true if the iteration has more

elements.

Page 21: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

• 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

Page 22: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

• 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

Page 23: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

23

9.5.6 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().

Page 24: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

• 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

Page 25: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

25

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

Page 26: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

26

9.5.7 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.

Page 27: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

• import java.util.Iterator;• …• for(Iterator<Cup7> myIterator =

myCollection.iterator(); myIterator.hasNext(); )• {• if((myIterator.next().getSeedCount()) <= 0)• myIterator.remove();• }

27

Page 28: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

28

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

Page 29: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

29

• 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

Page 30: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

30

• 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

Page 31: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

31

• 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

Page 32: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

32

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

Page 33: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

33

• 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

Page 34: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

34

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

Page 35: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

35

• 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

Page 36: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

36

• 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

Page 37: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

37

• 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()• {• }

Page 38: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

38

• 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);• }• }

Page 39: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

39

• 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<Seed>• {• private Rectangle cupRectangle;• private ArrayList<Seed> seedList;

• public Cup(int seedCountIn, int cupX, int cupY, int cupW, int cupH)• {• cupRectangle = new Rectangle(cupX, cupY, cupW, cupH);

• seedList = new ArrayList<Seed>();

• for(int i = 0; i < seedCountIn; i++)• {• Seed aSeed = new Seed();• seedList.add(aSeed);• }• }

Page 40: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

40

• public Cup(int cupX, int cupY, int cupW, int cupH)

• {• cupRectangle = new Rectangle(cupX, cupY,

cupW, cupH);• seedList = new ArrayList<Seed>();• }

• public Rectangle getRectangle()• {• return cupRectangle;• }

Page 41: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

41

• 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);• }

Page 42: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

42

• public ArrayList<Seed> getCupArrayList()• {• return seedList;• }

• public Iterator<Seed> iterator()• {• return new CupIterator(this);• }

• public int size()• {• return seedList.size();• }

• public boolean add(Seed seedIn)• {• return seedList.add(seedIn);• }• }

Page 43: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

43

• 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<Seed>• {• ArrayList<Seed> 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;• }• }

Page 44: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

44

• public Seed next() throws NoSuchElementException• {• if((arrayListIndex < cupArrayList.size() - 1) &&

(cupArrayList.size() > 0))• {• arrayListIndex++;• //System.out.println("next(), arrayListIndex value

after incrementing: " + arrayListIndex);• Seed seedRef = cupArrayList.get(arrayListIndex);• state = 1;• return seedRef;• }• else• throw new NoSuchElementException();• }

Page 45: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

45

• public void remove() throws IllegalStateException• {• if(state == 1)• {• //System.out.println("remove(),

arrayListIndex: " + arrayListIndex);• cupArrayList.remove(arrayListIndex);• arrayListIndex--;• state = 0;• }• else• throw new IllegalStateException();• }• }

Page 46: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

46

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

Page 47: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

47

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

Page 48: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

48

• 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

Page 49: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

49

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?

Page 50: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

50

Page 51: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

51

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

Page 52: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

52

• 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

Page 53: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

53

Page 54: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

54

Summary

• I won’t even bother to provide one…

Page 55: Chapter 28 Iterator Summary prepared by Kirk Scott 1.

55

The End