/* @(#)IntArrayListIterator.java 31 October 2005 */ /** * An IntArrayListIterator traverses an IntArrayList. */ public class IntArrayListIterator { IntArrayList list = null; IntArrayListNode node = null; int index = 0; /** * Constructs an iterator for the given IntArrayList. * * Throws NullPointerException if the given IntArrayList * is null. */ public IntArrayListIterator(IntArrayList thelist) { if (thelist == null) throw new NullPointerException ("Null list in IntArrayListIterator constructor"); list = thelist; node = list.getHead(); } /** * Returns true if there is a data item available in * the list at the current location of this iterator. */ public boolean hasData() { if (node == null) return false; if (index < node.getCount()) return true; IntArrayListNode next = node.getNext(); if (next == null) return false; return next.getCount() > 0; } /** * Returns the current data item. * * Advances the iterator to the next data item if more * data is available or to the end of the list. * * Throwns RuntimeException if the iterator is already * at the end of the list, that is, hasData() is false * when this method is called. */ public int getData() { if (! hasData()) throw new RuntimeException ("Request for data at the end of the list"); if (index >= node.getCount()) { node = node.getNext(); index = 0; } int contents = node.getDataItem(index); index++; return contents; } /** * Advances the iterator to the next data item if more * data is available or to the end of the list. * * Does nothing if the iterator is already at the end * of the list. */ public void advance() { if (node == null) return; if (index < node.getCount()) { index++; return; } node = node.getNext(); index = 0; } }