public class ArrayListWithIterator
1: import java.util.Arrays;
2: import java.util.Iterator;
3: import java.util.NoSuchElementException;
4: /**
5: A class that implements the ADT list by using a resizable array and
6: gives it an iterator.
7:
8: @author Frank M. Carrano
9: @author Timothy M. Henry
10: @version 4.0
11: */
12: public class ArrayListWithIterator<T> implements ListWithIteratorInterface<T>
13: {
14: private T[] list; // Array of list entries; ignore list[0]
15: private int numberOfEntries;
16: private boolean initialized = false;
17: private static final int DEFAULT_CAPACITY = 25;
18: private static final int MAX_CAPACITY = 10000;
19:
20: public ArrayListWithIterator()
21: {
22: this(DEFAULT_CAPACITY);
23: } // end default constructor
24:
25: public ArrayListWithIterator(int initialCapacity)
26: {
27: // Is initialCapacity too small?
28: if (initialCapacity < DEFAULT_CAPACITY)
29: initialCapacity = DEFAULT_CAPACITY;
30: else // Is initialCapacity too big?
31: checkCapacity(initialCapacity);
32:
33: // The cast is safe because the new array contains null entries
34: @SuppressWarnings("unchecked")
35: T[] tempList = (T[])new Object[initialCapacity + 1];
36: list = tempList;
37: numberOfEntries = 0;
38: initialized = true;
39: } // end constructor
40:
41: /* < Implementations of the methods of the ADT list go here;
42: you can see them in Chapter 13, beginning at Segment 13.5. */
43:
44: public Iterator<T> iterator()
45: {
46: return new IteratorForArrayList();
47: } // end iterator
48:
49: public Iterator<T> getIterator()
50: {
51: return iterator();
52: } // end getIterator
53:
54: private class IteratorForArrayList implements Iterator<T>
55: {
56: private int nextIndex; // Index of next entry in the iteration
57: private boolean wasNextCalled; // Needed by remove
58:
59: private IteratorForArrayList()
60: {
61: nextIndex = 1; // Iteration begins at list's first entry
62: wasNextCalled = false;
63: } // end default constructor
64:
65: // 15.16
66: public boolean hasNext()
67: {
68: return nextIndex <= numberOfEntries;
69: } // end hasNext
70:
71: //15.17
72: public T next()
73: {
74: if (hasNext())
75: {
76: wasNextCalled = true;
77: T nextEntry = list[nextIndex];
78: nextIndex++; // Advance iterator
79: return nextEntry;
80: }
81: else
82: throw new NoSuchElementException("Illegal call to next(); " +
83: "iterator is after end of list.");
84: } // end next
85:
86: // 15.18
87: public void remove()
88: {
89: if (wasNextCalled)
90: {
91: // nextIndex was incremented by the call to next, so it is
92: // 1 larger than the position number of the entry to be removed
93: ArrayListWithIterator.this.remove(nextIndex - 1);
94: nextIndex--; // Index of next entry in iteration
95: wasNextCalled = false; // Reset flag
96: }
97: else
98: throw new IllegalStateException("Illegal call to remove(); " +
99: "next() was not called.");
100: } // end remove
101: } // end IteratorForArrayList
102: } // end ArrayListWithIterator