Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
1 Iterators Outline and Required Reading: • Iterators (§ 5.5) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic 2 Iterators Iterator Pattern on an Array – code for traversing (iterating over) an array • each node visited in turn for (int i=0; i<a.length(); i++) { /* inspect or update a[i] */ } Iterator Pattern on a Sequence for (int i=0; i<S.size(); i++) { /* code that calls S.elementAtRank(i) */ } What if we want to traverse an arbitrary collection of objects - the underlying ADT, its implementation and “accessor” methods are not known to us?! 3 Iterators (cont.) Iterator – generic interface – provides a unified scheme to access all elements of a container (container = collection of objects) • independent from the specific organization of the collection • returns the elements according to their linear ordering ADT’s Iterator ADT hasNext() nextObject() remove() request result public interface Iterator { } public boolean hasNext(); /* determine if there are more elements */ public Object next(); /* retrieve the next element */ public void remove() throws UnsupportedOperationException; 4 Iterators (cont.) Example 1 [ Sequence ADT iterator ] class SequenceIterator implements Iterator { Sequence S; Position p; /* the sequence over which we’re iterating */ /* current position in S */ public SequenceIterator(Sequence Seq) { S = Seq; p = S.first(); /* start iterating from 1st position */ } boolean hasNext() { return (S.after(p) != null); } } Object nextObject() { Object o = p.element(); /* return element */ p = S.after(p); /* move iterator */ return o; } 5 Iterators (cont.) Now, let us use this iterator in order to print elements of a sequence. public void printElements(Sequence S) { … SequenceIterator SI = SequenceIterator(S); while (SI.hasNext()) { System.out.println(SI.nextObject()+”, “); } 6 Iterators in Java Interface Iterator in java.util.* [ from: http://java.sun.com/j2se/1.3/docs/api/java/util/Iterator.html ] public interface Iterator Method Summary boolean hasNext() Returns true if the iteration has more elements. Object next() Returns the next element in the interation. void remove() Removes from the underlying collection the last element returned by the iterator (optional operation). Java supports iterator() method in most of its “container” classes – this method returns an iterator over the elements of the given collection. 7 Iterators in Java (cont.) Example 2 [ Java-Vector iterator ] java.util.Vector class is one of the classes with a built-in iterator, i.e. with iterator() method. public static void printVector(java.util.Vector vec) { java.util.Iterator iter = vec.iterator(); while (iter.hasNext()) { } }; System.out.println(iter.next());