/** * IteratedArrayList.java * Class demo for CS 10 to show how to implement an Iterator object. * This functionality is already built into ArrayList, but this duplicates * it to show how it can be accomplished * * @author Scot Drysdale - 10/7/2014 */ import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class IteratedArrayList extends ArrayList { private static final long serialVersionUID = 1L; private class CS10Iterator implements Iterator { private int position; // Position before the next thing to be returned private boolean nextWasCalled; // True if next was called since the most recent remove private List myList; /** * Constructs an iterator for this ArrayList. */ private CS10Iterator(List aList) { position = -1; nextWasCalled = false; myList = aList; } /** * Implements the Iterator hasNext */ public boolean hasNext() { return position < myList.size()-1; } /** * Implements the Iterator next */ public T next() { if(hasNext()) { nextWasCalled = true; position++; return myList.get(position); } else { System.err.println("No next item"); return null; } } /** * Implements the Iterator remove */ public void remove() { if(nextWasCalled) { nextWasCalled = false; myList.remove(position); position--; // Removed the item at position, so must move one earlier } else System.err.println("No item to remove"); } } /** * Override the built-in linked list iterator */ public Iterator iterator() { return new CS10Iterator(this); } /** * A testing program */ public static void main(String [] args) { List aList = new IteratedArrayList(); aList.add("cat"); aList.add("dog"); aList.add("eagle"); Iterator iter = aList.iterator(); System.out.println(aList); System.out.println("hasNext on list: " + iter.hasNext()); System.out.println("result of next: " + iter.next()); iter.remove(); System.out.println("list after remove: "); System.out.println(aList); iter.remove(); System.out.println("result of next: " + iter.next()); System.out.println("result of next: " + iter.next()); System.out.println("hasNext on list: " + iter.hasNext()); iter.remove(); System.out.println("list after remove: "); System.out.println(aList); System.out.println("result of next: " + iter.next()); } }