You are on page 1of 37

Software Engineering

Lecture 4(a):
Iteration abstraction
2013

Outline
Why iteration abstraction?
Generator
Iteration in Java
Specify an iteration
Implement an iteration
Using iteration
List's iteration

2013

FIT330 Software Engineering

Why iteration abstraction?


Problem: how to conveniently and efficiently
iterate over a generic collection of objects?
Requirements: to support

incremental (run-time) access

unlimited collection size

all types of collections

2013

index-based (e.g. arrays) and non-index-based


collections (e.g. sets)

FIT330 Software Engineering

Example: IntSet elements


How to sum the elements of an IntSet s?
Basic algorithm:
for each element i in s.elements
add i to sum

return sum

How to obtain s.elements

2013

FIT330 Software Engineering

Some intuitive solutions


add a method to return an array of elements
add an index-based access method
add an observer that returns vector els

None is really suitable

2013

FIT330 Software Engineering

Iteration abstraction as a solution


An abstraction that provides generic access to
a collection's elements
incremental access:

ask & get

get: can also generate elements

supports unlimited collection size:

no bounds on size

supports all types of collections:

2013

assumes no knowlege of the collection's rep

specified as an interface
FIT330 Software Engineering

Generator

Generates the elements incrementally


Works differently depending on the collection
Pre-populated collections:

generate indices over the elements incrementally

Auto-populated collections:

2013

generate elements (and indices) incrementally

often has a bound condition

FIT330 Software Engineering

Pre-populated generator
IntSet

Vector
(els)

x1
P

2013

Generator

FIT330 Software Engineering

x2
...
xn

Auto-populated: PrimeSet
/**
* @overview
*
PrimeSet is an immutable
*
sub-type of IntSet, which contains a natural
*
sequence of prime numbers up to a given value.
*/

public class PrimeSet extends IntSet {


@DomainConstraint(type="Integer",min=1)
private Integer max;
elements up to max
}
are automatically
generated and added
to the set
2013

FIT330 Software Engineering

Iteration in Java
Generator is specified by interface
java.util.Iterator
Iterator defines 3 methods:

hasNext: ask

next: get

(optional) remove

Collections implement an iterator method:

2013

returns an Iterator object

may implement several

iterator methods can be stand-alone


FIT330 Software Engineering

10

iterator & Iterator


java.util.Iterator

IntSet
elements()

Vector
(els)

x1
P

2013

Generator

FIT330 Software Engineering

x2
...
xn
11

Multiple iterators
IntSet
elements()
GenA
P
GenB

Vector
(els)

x1
x2
...
xn

reverse
Elements()
2013

FIT330 Software Engineering

12

java.util.Iterator
<<interface>
Iterator
+ hasNext(): boolean
+ next(): Object
+ remove()
2013

FIT330 Software Engineering

13

Interface: Iterator
java.util.Iterator
Note:

2013

hasNext and next both check if more results to


return
next: modifies the state of generator if a new
result is returned
remove: only used for modifiable collections

FIT330 Software Engineering

14

hasNext()
/**
* @effects
*
if there are more elements to yield
*
return true
*
else
*
return false
*
*/
public boolean hasNext();

2013

FIT330 Software Engineering

15

next()
/**
* @modifies this
* @effects
*
if there are more results to yield
*
returns the next result
*
and modifies the state of
*
this to record the yield.
*
else
*
throws NoSuchElementException
*/
public Object next() throws NoSuchElementException;

2013

FIT330 Software Engineering

16

remove()
/**
* @effects
*
remove from the underlying collection the last
*
element returned by the call to next;
*
throw
*
UnsupportedOperationException if remove is not
*
supported,
*
IllegalStateException if next has not yet been
*
called, or remove has already been called after
*
the last call to next.
*
*
The behavior is unspecified if the underlying
*
collection is modified while the iteration is in
*
progress in any way other than by calling this
*
method.
*/
public void remove() throws UnsupportedOperationException,
IllegalStateException;
2013

FIT330 Software Engineering

17

Types with built-in iterators


Those that extend or implement interface
java.util.Iterable
Some common examples:

2013

Collection

List: ArrayList, LinkedList

Set

Queue

FIT330 Software Engineering

18

Specify an iteration
Common iterator method names: elements,
iterators
Typically contains @effects and @requires

rarely has @modifies

@effects:

appears before @requires

describes the generator

includes this as an implicit parameter

@requires: a standard statement this must


not be modified while generator is in use
2013

FIT330 Software Engineering

19

Specify a generator
A private inner class of the collection class
Implements java.util.Iterator
The rep keeps track of the iteration state
Rep invariant refers to attributes of the
enclosing class
AF: maps rep to a sequence of elements
Operations:

2013

hasNext and next

remove: if @modifies is defined

no repOK

FIT330 Software Engineering

20

Example: IntSet.elements
/**
* @effects
<pre>
*
if this is empty
*
throw EmptyException
*
else
*
return a generator that will produce all
*
the elements of this (as Integers), each
*
exactly once, in arbitrary order.</pre>
*
* @requires <tt>this</tt> must not be modified
*
while the generator is in use
*/

public Iterator elements()


throws EmptyException
2013

FIT330 Software Engineering

21

Generator: IntSet.IntSetGen
/**
* @overview
*
IntSet.IntSetGen represents a generator of the
*
elements of an IntSet.
* @attributes
* ind Integer
* @abstract_properties
* mutable(ind)=false /\ min(ind)=0 /\
* ind<IntSet.size()
* @abstraction_function
*
AF(c) = [x1,...] where each xi is in
*
c.IntSet.elements and are arranged in same
*
(arbitrary) order as c.IntSet.elements.
* @rep_invariant
*
ind >= 0 /\ ind < IntSet.size()
*/
2013

FIT330 Software Engineering

22

...
private class IntSetGen implements Iterator {
@DomainConstraint(type="Integer",mutable=false,
min=0)
private int ind;
}

2013

FIT330 Software Engineering

23

Implements an iteration

Implement the iterator method:

return a new generator object

Implement the generator:

hasNext:

next:

2013

pre-populated: checks the collection size


auto-populated: checks the bound condition
pre-populated: returns next element
auto-populated: generates and returns next element

Access outer class attributes or invoke its


methods
FIT330 Software Engineering

24

Example: IntSet
ch6.IntSet
Note:

elements: return a new instance of IntSetGen

IntSetGen:

hasNext: check ind against IntSet.size

next: return element at index ind and increment ind;


throwing an exception if fails to do so

2013

exception message points to method elements (not next)

FIT330 Software Engineering

25

IntSet.elements
public Iterator elements() throws EmptyException {
if (size() == 0)
throw new EmptyException("IntSet.elements");
return new IntSetGen();
}

2013

FIT330 Software Engineering

26

IntSet.IntSetGen
private class IntSetGen implements Iterator {
private int ind; // next index
// constructor method
public IntSetGen() {
ind = 0;
}
public boolean hasNext() {
return (ind < size());
}

2013

FIT330 Software Engineering

27

IntSet.IntSetGen
public Object next() throws NoSuchElementException {
if (hasNext()) {
Object next = elements.get(ind);
ind++;
return next;
}
throw new
NoSuchElementException("IntSet.elements");
}
public void remove() {
// do nothing
}
}
2013

FIT330 Software Engineering

28

Advanced example: PrimeSet


Auto-populated generator:
PrimeSet

Vector
(els)

p1
P

Generator
max

bound condition: elements are max


2013

FIT330 Software Engineering

29

PrimeSet

E xercise

ch6.PrimeSet
Note:

Extra attribute: max

Constructor invokes super's first, then initialises max

throws NotPossibleException if max is invalid

repOK: invokes super.repOK() first, then performs


additional validation

genElements iterator differs from IntSet.elements

PrimeGen:

2013

hasNext(): check if more primes max

next(): find next prime, add to set and return


FIT330 Software Engineering

30

Using iteration

Iterator method's @requires clause must be


observed
Generator object is used via iterator
methods
Use while loop to iterate the elements
Loop condition is controlled by:

2013

hasNext or

NoSuchElementException thrown by next

FIT330 Software Engineering

31

Example
ch6.usage.IteratorUsage
Note:

evenNumbersUpTo: pre-populate a set of even


numbers up to some value and print:

2013

loop controlled by hasNext

FIT330 Software Engineering

32

Loop controlled by hasNext


// loop controlled by hasNext
IntSet iset = new IntSet();
for (int i = 0; i < 100; i++)
// even numbers
if (i % 2 == 0) iset.insert(i);
Iterator g = iset.elements();
while (g.hasNext()) {
int x = (Integer) g.next();
// use x
}

2013

FIT330 Software Engineering

33

Loop controlled by exception


// loop controlled by exception
PrimeSet pset = new PrimeSet(100);
Iterator g = pset.elements();
try {
while (true) {
int x = (Integer) g.next();
// use x
}
} catch (NoSuchElementException e) {
// no more elements
}

E xercise
2013

FIT330 Software Engineering

34

List's iteration
If your data type is a List, then simply
invokes its iterator method:
iterator(): Iterator

Example: ch7.lists.ListExample

Note: to obtain the iterator:


Iterator it = list.iterator();

2013

FIT330 Software Engineering

35

Summary
Iteration abstraction provides a convenient and
efficient generic method to iterate the elements
of a collection
Iteration abstraction is defined by a
combination of an iterator method and a
generator
iterator method creates a new generator
Generator implements
java.util.Iterator and is specified as an
inner class
Java's List classes implement iterators

2013

FIT330 Software Engineering

36

Questions?

2013

FIT330 Software Engineering

37

You might also like