container traversal cmput 115 - lecture 20 department of computing science university of alberta...
Post on 19-Dec-2015
218 views
TRANSCRIPT
Container TraversalContainer Traversal
Cmput 115 - Lecture 20
Department of Computing Science
University of Alberta©Duane Szafron 2000
Some code in this lecture is based on code from the book:Java Structures by Duane A. Bailey or the companion structure package
Revised 2/23/00
©Duane Szafron 2000
2
About This LectureAbout This Lecture
In this lecture we will learn about traversing containers.
In Java, traversal is commonly done using the Enumeration and Iterator Interfaces.
©Duane Szafron 2000
3
OutlineOutline
Traversals
The Enumeration Interface
The Iterator Interface
Vector Iterators
©Duane Szafron 2000
4
Container TraversalContainer Traversal
A traversaltraversal is an operation that accesses each element of a container once and performs some operation on the element as it is accessed.
Common traversals:– Output all elements in a container.– Create a new container that contains all of the
elements of the old one.– Compute the index of the first element of an
indexed container that is equal to a key.– Add up the values of all Integer elements in a
container.
©Duane Szafron 2000
5
Four Approaches to TraversalFour Approaches to Traversal There are four common approaches to
traversal:
– Explicit traversal operations– Cursors– Method Parameters– Iterators
©Duane Szafron 2000
6
Explicit OperationsExplicit Operations The explicit traversal operations approach provide a different container operation for each traversal, like:
outputElements(), findIndex (Object), sumOfElements(), capitalizeElements()
One disadvantage of this approach is that similar traversal code is repeated in each traversal operation (e.g., we need code to output and to sum the elements in a container).
A second disadvantage is that new traversals may be required after the container class has been finished.
©Duane Szafron 2000
7
Cursor TraversalsCursor Traversals The cursor traversalcursor traversal approach provide operations that give
access to a current element (cursor) and operations that move the cursor, and let the user write the different traversals as needed. Example: cursor = this.head; // partial traversal
while ((cursor != null) && (!cursor.value().equals(anObject))
cursor = cursor.next();
The disadvantage of this approach is that the user must write the traversals– The user may make mistakes.– This is duplication of effort for multiple users.
©Duane Szafron 2000
8
A Container with a CursorA Container with a Cursor
4 7 1 5 3
aContainer
first cursor
©Duane Szafron 2000
9
A Container with a CursorA Container with a Cursor A cursor protocol:
– resetCursor()– moveCursor()– cursorAtEnd()– cursorElement()
4 7 1 5 3aContainer
cursor first
©Duane Szafron 2000
10
Method Parameters - applyMethod Parameters - apply Provide a few basic traversal operations that apply
method parametersmethod parameters to the elements.
We could add the method applyUsing(Object, Method) to a container class which takes an Object and a method as arguments and applies the method to the Object once for each element of the container with the element as an argument.
For example, if VectorVector provided this method we could print all of the elements in the Vector using:myVector.applyUsing(System.out, println(Object))
We could use the same method to copy the Vector:myVector.applyUsing(newVector, addElement(Object))
©Duane Szafron 2000
11
Method Parameters - findMethod Parameters - find We could add the method find(Method)find(Method) to a container
class which takes a method as an argument, applies the method to each element of the container and returns the index for the first application that returns true.
For example, if Vector provided this method we could find the index of an Object using:
myVector.find(equals(Object))
Unfortunately, Java does not support methods as parameters, but other languages (Pascal, C, C++ and Smalltalk) do.
©Duane Szafron 2000
12
Iterators and EnumerationsIterators and Enumerations The Iterator traversal approach is similar to the cursor
approach, but a new class of object is provided so that the container class provider hides the cursor.
Java introduces two interfaces to support iterator-style traversals: Enumeration and Iterator.
The Enumeration Interface supports container traversal in which the order is not deterministic.
The Iterator Interface supports ordered traversal of containers.
©Duane Szafron 2000
13
Enumeration HierarchyEnumeration Hierarchy In the java.* packages, Enumerator and Iterator are
independent Interfaces. In the structure package, Iterator extends Enumerator. The Iterator Interface in the structure package defines
different methods than the Iterator Interface in the java.* packages.
Enumerator
Iterator
©Duane Szafron 2000
14
Creating Enumerations & Iterators Creating Enumerations & Iterators
The user never creates an Enumeration or Iterator object explicitly.
Instead, each container class provides a method that returns an object that implements the Enumeration or Iterator interface.
For example, the Collection Interface defines: public Iterator elements(); // post: return an iterator for traversing the // collection
©Duane Szafron 2000
15
Enumeration & Iterator Classes Enumeration & Iterator Classes
The elements() method is implemented in each class that implements the Collection Interface.
The class of the Object returned is hidden from the user of the collection class.
The Enumeration or Iterator class is defined inside of the collection class, but is not made public.
The Enumeration or Iterator object can only be used by sending it messages defined in the public interface.
©Duane Szafron 2000
16
Structure Interface - EnumeratorStructure Interface - Enumeratorpublic interface Enumerator {
public boolean hasMoreElements();// pre: the associated container has not been changed// since the last time this method was invoked// post: returns true iff at least one element of the// associated container has yet to be enumerated.
public Object nextElement();// pre: the associated container has more // unenumerated elements// post: returns an unenumerated element of the// associated container and marks it as enumerated
}
code based on Bailey pg. 155
©Duane Szafron 2000
17
Enumerator ExampleEnumerator Examplepublic static void main (String[ ] args) {
Collection container;Enumeration enumerator;
container = new SetList();container.add(“Fred”);container.add(“Barney”);enumerator = container.elements();while (enumerator.hasMoreElements())
System.out.println(enumerator.nextElement());}
code based on Bailey pg. 158
BarneyFred
©Duane Szafron 2000
18
Structure Interface - IteratorStructure Interface - Iteratorpublic interface Iterator extends Enumeration {
public Object nextElement ();// pre: the associated container has more // uniterated elements// post: returns the next uniterated element of the// associated container and marks it as iterated
public void reset ();// post: Makes the Iterator ready for a new traversal
public Object value ();// pre: the associated container has more // uniterated elements// post: Returns the next element to be iterated
}
code based on Bailey pg. 157
©Duane Szafron 2000
19
Iterator ExampleIterator Examplepublic static void main (String[ ] args) {
Vector container;Iterator iterator;
container = new Vector();container.addElement(“Fred”);container.addElement(“Barney”);iterator = container.elements();while (iterator.hasMoreElements()) {System.out.println(iterator.value());System.out.println(iterator.nextElement());}
}
code based on Bailey pg. 158
FredFredBarneyBarney
©Duane Szafron 2000
20
VectorIterator - VectorIterator - State and ConstructorState and Constructor
class VectorIterator implements Iterator {// This class is not a public class// It is implemented inside of the file: Vector.java that// declares the public class: Vector
protected Vector vector;protected int current;
public VectorIterator(Vector v) {// not really public// post: intitalizes Vector and resets the traversal
this.vector = v;this.reset();
}
code based on Bailey pg. 159
©Duane Szafron 2000
21
VectorIterator - VectorIterator - Enumeration InterfaceEnumeration Interface
/* Interface Enumeration Methods */public boolean hasMoreElements () {// pre: the associated container has not been changed// since the last time this method was invoked// post: returns true iff at least one element of the
// associated container has yet to be enumerated.
return this.current < this.vector.size();}
public Object nextElement () {// pre: the associated container has more uniterated elements// post: returns the next uniterated element of the// associated container and marks it as iterated
return this.vector.elementAt(this.current++);}
code based on Bailey pg. 159
©Duane Szafron 2000
22
VectorIterator - VectorIterator - Iterator InterfaceIterator Interface
/* Interface Iterator Methods */public void reset () {// post: Makes the Iterator ready for a new traversal
this.current = 0;}
public Object value ();// pre: the associated container has more // uniterated elements// post: Returns the next element to be iterated
return this.vector.elementAt(this.current);}
}
code based on Bailey pg. 160
©Duane Szafron 2000
23
Class Vector - Class Vector - elements()elements()
public Iterator elements () {// post: returns an Iterator for traversing the elements
return new VectorIterator (this);}
code based on Bailey pg. 158
©Duane Szafron 2000
24
Some Principles from the TextbookSome Principles from the Textbook
14. Never modify a data structure while an associated Enumeration is live.
15. Assume that values returned by Iterators are read-only.
principles from Bailey ch. 8