// File: Lister.java from the package edu.colorado.nodes
// Complete documentation is available from the Lister link in:
// http://www.cs.colorado.edu/~main/docs/
package edu.colorado.nodes;
import java.util.Iterator;
import java.util.NoSuchElementException;
import edu.colorado.nodes.Node;
/******************************************************************************
* A Lister
implements Java's Iterator<E>
* interface for a linked list made from Node<E>
nodes.
* Note that this implementation of an Iterator<E>
does not
* support the remove
method. Any activation of remove
* results in an
* UnsupportedOperationException
.
*
* Java Source Code for this class:
*
* http://www.cs.colorado.edu/~main/edu/colorado/nodes/Lister.java
*
* @author Michael Main
* (main@colorado.edu)
*
* @version Feb 10, 2016
*
* @see Node
******************************************************************************/
public class Lister implements Iterator
{
// Invariant of the Lister class:
// The instance variable list is the head reference for the linked list
// that contains the elements that have not yet been provided by
// the next method. If there are no more elements to provide, then
// list is the null reference.
private Node list;
/**
* Initialize a Lister with a specified linked list.
* @param head
* a head reference for a linked list of objects
* Postcondition:
* Subsequent activations of next
will return the elements
* from this linked list, one after another. If the linked list changes
* in any way before all the elements have been returned, then the
* subsequent behavior of this Lister
is unspecified.
**/
public Lister(Node head)
{
list = head;
}
/**
* Determine whether there are any more elements in this Lister.
* @return
* true
if there are more elements in this
* Lister
; false
otherwise.
**/
public boolean hasNext( )
{
return (list != null);
}
/**
* Retrieve the next element of this Lister
.
* a bag whose contents will be added to this bag
* Precondition:
* hasMoreElements()
must be true
.
* @return
* The return value is the next element of this Lister
.
* Note that each element is only returned once, and then the
* Lister
automatically advances to the next element.
* @exception NoSuchElementException
* Indicates that hasMoreElements()
is false
.
**/
public E next( )
{
E answer;
if (!hasNext( ))
throw new NoSuchElementException("The Lister is empty");
answer = list.getData( );
list = list.getLink( );
return answer;
}
public void remove( )
{
throw new UnsupportedOperationException("Lister.remove not allowed");
}
}