Traditional Method of Iterating Through an Array
int [] arr = new int [...]; ... for (int i = 0; i < arr.length; i++) { // Do something with arr[i] }That's fine, but:
arr.length-1
arr[i]
)
arr.length
arr[i]
Revisiting the Iterator Interface
interface Iterator { boolean hasNext(); Object next(); }
hasNext
eliminates the need to know the terminating condition
next
eliminates the need to know how to access the next element
implement
the interface
An Iterator for Arrays
class ArrayIterator implement Iterator{ }
class ArrayIterator implement Iterator{ private int currentIndex; }
currentIndex
to 0
i = 0
of the traditional method
class ArrayIterator implement Iterator{ ArrayIterator() { currentIndex = 0; } private int currentIndex; }
hasNext
Method
hasNext
tests if we've reached the last element
i < arr.length
class ArrayIterator implement Iterator{ ArrayIterator() { currentIndex = 0; } boolean hasNext() {return currentIndex < arr.length;} private int currentIndex; }
class ArrayIterator implement Iterator { ArrayIterator(int [] arr) { this.arr = arr; currentIndex = 0; } boolean hasNext() {return currentIndex < arr.length;} private int [] arr; private int currentIndex; }
next
Method
next
retrieves the next element
class ArrayIterator implement Iterator { ArrayIterator(int [] arr) { this.arr = arr; currentIndex = 0; } boolean hasNext() {return currentIndex < arr.length;} int next() { int hold = arr[currentIndex]; currentIndex++; return hold; } private int [] arr; private int currentIndex; }
hasNext
and next
be
part of the DynArr class itself-- why introduce a new class
for (int i = 0; i < arr.length; i++) { count = 0; for (j = i+1; j < arr.length; j++) if (arr[i] == arr[j]) count++; System.out.println("Element " + arr[i] + " at index " + i + " is repeated " + count + " times"); }
for (int i = 0; i < arr.length; i++) { count = 0; for (i = i+1; j < arr.length; i++) // ??? if (arr[i] == arr[i]) count++; System.out.println("Element " + arr[i] + " at index " + i + " is repeated " + count + " times"); }Remember that the state of the iterator (the currentIndex instance variable) corresponds to the loop index