Source of ArrayListWithIterator.java


  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 5.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 integrityOK = 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:       integrityOK = false;

 29:       // Is initialCapacity too small?
 30:       if (initialCapacity < DEFAULT_CAPACITY)
 31:          initialCapacity = DEFAULT_CAPACITY;
 32:       else // Is initialCapacity too big?
 33:          checkCapacity(initialCapacity);
 34:       
 35:       // The cast is safe because the new array contains null entries
 36:       @SuppressWarnings("unchecked")
 37:       T[] tempList = (T[])new Object[initialCapacity + 1];
 38:       list = tempList;
 39:       numberOfEntries = 0;
 40:       integrityOK = true;
 41:         } // end constructor
 42:    
 43: /* < Implementations of the methods of the ADT list go here;
 44:      you can see them in Chapter 11, beginning at Segment 11.5. */
 45:    
 46:    public Iterator<T> iterator()
 47:    {
 48:       return new IteratorForArrayList();
 49:    } // end iterator
 50:    
 51:    public Iterator<T> getIterator()
 52:    {
 53:       return iterator();
 54:    } // end getIterator
 55:    
 56:    private class IteratorForArrayList implements Iterator<T>
 57:    {
 58:       private int     nextIndex;     // Index of next entry in the iteration
 59:       private boolean wasNextCalled; // Needed by remove
 60:      
 61:       private IteratorForArrayList()
 62:       {
 63:          nextIndex = 1;         // Iteration begins at list's first entry
 64:          wasNextCalled = false;
 65:       } // end default constructor
 66:      
 67:       // Implementations of the methods in the interface Iterator go here.
 68:       
 69:    } // end IteratorForArrayList
 70: } // end ArrayListWithIterator