Fri Jun 20 09:36:43 EDT 2003 For COM1204, all Iterator test code ==> Iterator1TestArr.java <== /** * Tests Iterator1 example for both array and linked list collections. * * @author R. P. Futrelle * @version 20 June 2003 (started 19 June 2003) */ class Iterator1TestArr { public static void main(String[] args) { MyArrayCollection myArr = new MyArrayCollection(10); for(int i=0; i < 8; i++) { myArr.add("item " + i); } MyIterator myIt = myArr.iterator(); System.out.println("Iterating on my array collection:"); while(myIt.hasNext()) { System.out.println((String)myIt.next()); } } // main() } ==> MyArrayCollection.java <== /** * A collection built on an array and returning a MyIterator subclass. * * @author R. P. Futrelle * @version 20 June 2003 (started 19 June 2003) */ class MyArrayCollection { Object[] storesIt; int maxIndexFilled; int _capacity; // Test this class using main(), w/o iterator public static void main(String[] args){ MyArrayCollection tester = new MyArrayCollection(3); tester.add("string1"); tester.add("string2"); tester.add("string3"); tester.add("string4"); tester.add("string5"); System.out.println(); for(int i = 0; i <= tester.maxIndexFilled; i++) System.out.println(tester.storesIt[i]); tester.clear(); tester.add("string10"); tester.add("string11"); System.out.println(); for(int i = 0; i <= tester.maxIndexFilled; i++) System.out.println(tester.storesIt[i]); /* results: string1 string2 string3 string10 string11 */ } // main() MyArrayCollection(int capacity) { _capacity = capacity; storesIt = new Object[_capacity]; init(); } void init() { maxIndexFilled = -1; } // init() MyIterator iterator() { return new MyArrayIterator(this); } boolean add(Object obj) { if(maxIndexFilled >= _capacity - 1) return false; storesIt[++maxIndexFilled] = obj; return true; } void clear() { init(); } } // MyArrayCollection ==> MyArrayIterator.java <== /** * Specialized Iterator for MyArrayCollection. * * @author R. P. Futrelle * @version 20 June 2003 (started 19 June 2003) */ class MyArrayIterator implements MyIterator { int nextIndexToDo; MyArrayCollection _collection; MyArrayIterator(MyArrayCollection collection) { _collection = collection; nextIndexToDo = 0; } public boolean hasNext() { return nextIndexToDo <= _collection.maxIndexFilled; } // hasNext() public Object next() { // NOT best practice, need exception if (nextIndexToDo > _collection.maxIndexFilled) return null; return _collection.storesIt[nextIndexToDo++]; // increment after use } // next() } // MyArrayIterator ==> MyIterator.java <== /** * Interface for my Iterator type. * * @author R. P. Futrelle * @version 20 June 2003 (started 19 June 2003) */ interface MyIterator { boolean hasNext(); Object next(); }