JAVA   15

ArrayIntListIterator

Guest on 11th May 2022 04:36:23 PM

  1. // The ArrayIntListIterator class provides a set of utilities for iterating
  2. // over an ArrayIntList and possibly removing values from the list.
  3.  
  4. import java.util.*;
  5.  
  6. public class ArrayIntListIterator {
  7.     private ArrayIntList list;      // list to iterate over
  8.     private int position;           // current position within the list
  9.     private boolean removeOK;       // whether it's okay to remove now
  10.  
  11.     // post: constructs an iterator for the given list
  12.     public ArrayIntListIterator(ArrayIntList list) {
  13.         this.list = list;
  14.         position = 0;
  15.         removeOK = false;
  16.     }
  17.  
  18.     // post: returns true if there are more elements left, false otherwise
  19.     public boolean hasNext() {
  20.         return position < list.size();
  21.     }
  22.  
  23.     // pre : hasNext() (throws NoSuchElementException if not)
  24.     // post: returns the next element in the iteration
  25.     public int next() {
  26.         if (!hasNext()) {
  27.             throw new NoSuchElementException();
  28.         }
  29.         int result = list.get(position);
  30.         position++;
  31.         removeOK = true;
  32.         return result;
  33.     }
  34.  
  35.     // pre : next() has been called without a call on remove (throws
  36.     //       IllegalStateException if not)
  37.     // post: removes the last element returned by the iterator
  38.     public void remove() {
  39.         if (!removeOK) {
  40.             throw new IllegalStateException();
  41.         }
  42.         list.remove(position - 1);
  43.         position--;
  44.         removeOK = false;
  45.     }
  46. }

Raw Paste


Login or Register to edit or fork this paste. It's free.