CSE143 Sample Program handout #6 Sample client code: Class IntListSample2.java --------------------------------------------- // Stuart Reges // 4/4/05 // // Demonstrates some basic use of an IntListIterator public class IntListSample2 { public static void main(String[] args) { IntList list = new IntList(25); for (int i = 0; i < 25; i++) list.add((int)(5* Math.random())); System.out.println(list); IntListIterator i = list.iterator(); while (i.hasNext()) if (i.next() == 3) i.remove(); System.out.println(list); } } Sample Execution of IntListSample2 ---------------------------------- [1, 0, 0, 3, 0, 3, 3, 3, 4, 2, 1, 2, 1, 1, 2, 2, 4, 4, 1, 0, 2, 1, 2, 3, 1] [1, 0, 0, 0, 4, 2, 1, 2, 1, 1, 2, 2, 4, 4, 1, 0, 2, 1, 2, 1] New Method added to IntList.java -------------------------------- // post: returns an iterator for this list public IntListIterator iterator() { return new IntListIterator(this); } Class IntListIterator.java -------------------------- // Stuart Reges // 4/4/05 // // The IntListIterator class provides a set of utilities for iterating over // an IntList and possibly removing values from the list. import java.util.*; public class IntListIterator { private IntList list; // list to iterate over private int position; // current position within the list private boolean removeOK; // whether it's okay to remove now // pre : list != null // post: constructs an iterator for the given list public IntListIterator(IntList list) { this.list = list; this.position = 0; this.removeOK = false; } // post: returns true if there are more elements left, false otherwise public boolean hasNext() { return this.position < this.list.size(); } // pre : hasNext() // post: returns the next element in the iteration public int next() { if (!this.hasNext()) throw new NoSuchElementException(); int result = this.list.get(position); this.position++; this.removeOK = true; return result; } // pre : next() has been called without a call on remove (i.e., at most one // call on remove per call on next) // post: removes the last element returned by the iterator public void remove() { if (!this.removeOK) throw new IllegalStateException(); this.list.remove(this.position - 1); this.position--; this.removeOK = false; } }
Stuart Reges
Last modified: Mon Apr 4 14:15:43 PDT 2005