CS 280 Data Structures Professor John Peterson
Project 9 Questions? IS280
Exam #2 Next Wednesday. All period. I’ll answer review questions Monday. This will cover links and recursion.
The Final Link Topic An Iterator is a class that returns values from a collection or some other sequence one at a time. This uses a bunch of built-in Java classes and special syntax. Iterator for loops: for (x : value) {body} This extracts items one by one from the collection x and executes the body
The Syntax for (x : v) { body} is the same as temp = v.iterator(); while (temp.hasNext()) { x = temp.next(); body}
Iterable Interface These are built in: public interface Iterable { Iterator iterator(); } public interface Iterator { boolean hasNext(); \\Returns true if the iteration has more elements. E next(); \\ Returns the next element in the iteration. void remove(); \\ Removes from the underlying collection the last element returned by the iterator (optional operation). }
Example: A Link Iterator public class ListIterator implements Iterator { public Link here; public ListIterator(Link here) { this.here = here; } public boolean hasNext() { return here != null; } public T next() { T res = here.data; here = here.link; return res; } public void remove() { System.out.print("Error: can't remove lists!"); }
Link public class Link implements Iterable { … public Iterator iterator() { return new ListIterator(this); }
Example: Printing public static String printList(Link x) { if (x == null) return "{}"; // Why? boolean first = true; String res = ""; for (T v : x) { res = res + (first ? "{" : ", "); res = res + v.toString(); first = false; } return res + "}"; }