Download presentation
Presentation is loading. Please wait.
1
CS 280 Data Structures Professor John Peterson
2
Project 9 Questions? http://wiki.western.edu/mcis/index.php/C IS280
3
Exam #2 Next Wednesday. All period. I’ll answer review questions Monday. This will cover links and recursion.
4
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
5
The Syntax for (x : v) { body} is the same as temp = v.iterator(); while (temp.hasNext()) { x = temp.next(); body}
6
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). }
7
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!"); }
8
Link public class Link implements Iterable { … public Iterator iterator() { return new ListIterator(this); }
9
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 + "}"; }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.