Lect4a Iteration
Post on 18-Jul-2016
238 Views
Preview:
DESCRIPTION
Transcript
Software Engineering
2013
Lecture 4(a):Iteration abstraction
2013 FIT330 Software Engineering 2
Outline
◊ Why iteration abstraction?
◊ Generator
◊ Iteration in Java
◊ Specify an iteration
◊ Implement an iteration
◊ Using iteration
◊ List's iteration
2013 FIT330 Software Engineering 3
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
– index-based (e.g. arrays) and non-index-based collections (e.g. sets)
1
2013 FIT330 Software Engineering 4
Example: IntSet elements
◊ How to sum the elements of an IntSet s?
◊ Basic algorithm:
for each element i in s.elementsadd i to sum
return sum
?How to obtain s.elements
2013 FIT330 Software Engineering 5
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 6
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:● assumes no knowlege of the collection's rep● specified as an interface
2013 FIT330 Software Engineering 7
Generator
◊ Generates the “elements” incrementally
◊ Works differently depending on the collection
◊ Pre-populated collections:● generate indices over the elements incrementally
◊ Auto-populated collections:● generate elements (and indices) incrementally● often has a bound condition
2
2013 FIT330 Software Engineering 8
Pre-populated generator
Generator
x1
x2
...x
n
Vector(els)
IntSet
P
2013 FIT330 Software Engineering 9
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 10
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:● returns an Iterator object● may implement several● iterator methods can be stand-alone
3
2013 FIT330 Software Engineering 11
iterator & Iterator
Generator
x1
x2
...x
n
Vector(els)
IntSet
P
elements()
java.util.Iterator
2013 FIT330 Software Engineering 12
Multiple iterators
GenA
x1
x2
...x
n
Vector(els)
IntSet
P
elements()
reverseElements()
GenB
2013 FIT330 Software Engineering 13
java.util.Iterator
+ hasNext(): boolean+ next(): Object+ remove()
Iterator
<<interface>
2013 FIT330 Software Engineering 14
Interface: Iterator
java.util.Iterator
◊ Note:● 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
2013 FIT330 Software Engineering 15
hasNext()
/** * @effects * if there are more elements to yield * return true * else * return false * */ public boolean hasNext();
2013 FIT330 Software Engineering 16
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 17
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 18
Types with built-in iterators
◊ Those that extend or implement interface java.util.Iterable
◊ Some common examples:● Collection● List: ArrayList, LinkedList● Set● Queue
2013 FIT330 Software Engineering 19
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”
4
2013 FIT330 Software Engineering 20
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: ● hasNext and next● remove: if @modifies is defined● no repOK
2013 FIT330 Software Engineering 21
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 22
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 23
...
private class IntSetGen implements Iterator {
@DomainConstraint(type="Integer",mutable=false,
min=0)
private int ind;
}
2013 FIT330 Software Engineering 24
Implements an iteration
◊ Implement the iterator method:● return a new generator object
◊ Implement the generator:● hasNext:
– pre-populated: checks the collection size– auto-populated: checks the bound condition
● next: – pre-populated: returns next element– auto-populated: generates and returns next element
● Access outer class attributes or invoke its methods
5
2013 FIT330 Software Engineering 25
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● exception message points to method elements (not next)
2013 FIT330 Software Engineering 26
IntSet.elements
public Iterator elements() throws EmptyException { if (size() == 0) throw new EmptyException("IntSet.elements"); return new IntSetGen();}
2013 FIT330 Software Engineering 27
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 28
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 29
Advanced example: PrimeSet
◊ Auto-populated generator:
Generator
p1
max
Vector(els)
PrimeSet
P
bound condition: elements are max
2013 FIT330 Software Engineering 30
PrimeSet
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:
– hasNext(): check if more primes max
– next(): find next prime, add to set and return
E xercise
2013 FIT330 Software Engineering 31
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:● hasNext or ● NoSuchElementException thrown by next
6
2013 FIT330 Software Engineering 32
Example
ch6.usage.IteratorUsage
◊ Note:● evenNumbersUpTo: pre-populate a set of even
numbers up to some value and print:– loop controlled by hasNext
2013 FIT330 Software Engineering 33
Loop controlled by hasNext
// loop controlled by hasNextIntSet 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 34
Loop controlled by exception
// loop controlled by exceptionPrimeSet 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 35
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();
7
2013 FIT330 Software Engineering 36
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 37
Questions?
top related