The Iterator Interface ------------------------------ To make our programs even more generic, we can use the Iterator interface. The interface looks like this... Look up the spec in the API... interface Iterator { public boolean hasNext(); //Returns the answer to the question "are there anymore elements left?" public Object next(); //Returns the current Object and moves to the next element in the data // structure public void remove(); //Removes the current element from the data structure } Here is the code we wrote in section for an IntList class... class IntNode { int data; IntNode next; } public class IntList { IntNode head; public IntList() {} public ListIter makeIter() { return new ListIter(); } protected class ListIter implements Iterator { IntNode current = head; public boolean hasNext() { return (current == null); } public Object next() { int currValue = current.num; current = current.next; return new Integer(currValue); } public void remove() { } } } OK, then we had problems trying to use this method. Below is a main class that has the search() method that we did in section, but it also has a main() too. Notice that it builds the iterator using the makeIter() method made in the IntList class. We then pass that iterator that we made into our search method to enumerate the items. public class AnotherClass { //Returns true if we "find" is in the data structure to which "i" points public static boolean search(Iterator i, Comparable find) { while (i.hasNext()) { if (find.compareTo(i.next())==0) return true; } return false; } public static void main(String args[]) { IntList list = new IntList(); //Make list... IntList.ListIter i = list.makeIter(); search(i,new Integer(5)); } } Q: Why did we pass in an Iterator into search() rather than an IntList? A: This is the beauty of the Iterator interface. This search() method can be used with any data structure if we pass in an Iterator. So if I had a class IntTree, and IntTree has an Iterator associated with it, I can call search() on this IntTree without writing another search() method. This is the essence of generic programming. Q: Why did we pass in a Comparable into search() rather than an int? A: Again, it is a principle of generic programming. This search() method can be used with any data type contained within the data structure. So if I had a ComplexList, a linked list of Complex objects, then I could still use this search() method without writing a new one. These are the same reasons described in the notes on Comparable. ---------------------------------------------------------- Confused? E-mail me... rgl8@cornell.edu