// File: BogusList2.java // Version 2 of the generic BogusList class. // The implementation of the list has been changed from a generic array // to a generic ArrayList, but since the interface remains the same, all // client code that worked with the previous version will also work // with this version, with no modification. // This demonstrates the OOP principle of "information hiding." // NOTE: Note again that this class is not "safe!" Users must heed // these warnings: // 1. Do not ask if there are more items unless you have set the iterator! // 2. Do not try to retrieve the next item unless you have set the iterator! // 3. Do not try to retrieve the next item unless you are sure there IS one! // 4. Do not run with scissors! package lists ; import java.util.ArrayList ; /** * Implements a simple list with limited functionality. */ public class BogusList2 { private ArrayList item ; // list implemented as ArrayList private int iterator ; // list iterator /** * Create an empty list */ public BogusList2() { item = new ArrayList() ; } /** * Append an item to the end of the list * @param newItem the object to be appended */ public void append (E newItem) { item.add(newItem) ; } /** * Make the list empty. */ public void clear() { item = new ArrayList() ; } /** * Is a particular object on the list? * * Precondition: The equals() method must be overridden in whatever class * of objects is stored on the list * * @param target the object to search for * @return true if target is on the list, false if not. */ public boolean contains(E target) // linear search { for ( E current : item ) { if ( current.equals(target) ) return true ; } return false ; } /** * Return a String containing all the objects on the list * * Precondition: The toString() method must be overridden in whatever * class of objects is stored on the list * * @return the list as a String */ public String toString() { String out = "" ; for ( E current : item ) { out += current + " " ; } return out + "\n" ; } // ************* iterator methods ************* /** * Set the iterator to position just before the start of the list */ public void setIterator() { iterator = -1 ; } /** * Are there more items on the list? * * Precondition: The iterator must be set * * @return true if at least one more item on the list, false if not */ public boolean more() { return iterator < item.size() - 1 ; } /** * Advance iterator to the next item on the list and return it * * Precondition: The iterator must be set and must not be pointing to * the last object on the list * * @return the object to which the iterator is pointing */ public E next() { return item.get(++iterator) ; } } // =========================================================================