NEList.java

/**
 * Concrete implementation of the non-empty list interface, INEList.
 * Contains two pieces of data:
 * first: an Object representing the first data element
 * rest: an IList object representing the rest of this non-emptylist.
 * When a class contains other objects that are isomorphic to itself,
 * this class is called a composite.
 * Provides concrete code for
 * a constructor to initialize this NEList to a given first and rest,
 * the getFirst() method for accessing the first data element,
 * the getRest() method for accesssing the rest of the list.
 * It has concrete implementations of all the methods inherited from IList.
 * @author Dung X. Nguyen
 * @since Copyright 2003 by DXN - All rights reserved
 */
public class NEList implements INEList {

    /**
     * The first data element of this NEList.
     */
    private Object _first;
    /**
     * The rest or "tail" of this NEList.
     * Data Invariant: _rest != null;
     */
    private IList _rest;

    /**
     * Initializes this NEList to a given first and rest.
     * @param first the first data element of this NEList.
     * @param tail != null, the rest of this NEList.
     */
    public NEList(Object first, IList tail) {
        _first = first;
        _rest = tail;
    }

    /**
     * Returns the first data element of this NEList.
     */
    public Object getFirst() {
        return _first;
    }

    /**
     * Returns the rest of this NEList.
     */
    public IList getRest() {
        return _rest;
    }

    /**
     * Recursively computes the length of _rest and adds 1 to the result.
     * @return an int >= 1.
     */
    public int getLength() {
        return 1 + _rest.getLength();
    }

    /**
     * Concatenates _rest with the given IList and "cons" _first to the result.
     * @param rhs the IList on the right hand side.
     * @return an INEList.
     */
    public IList concatenate(IList rhs) {
        return new NEList(_first, _rest.concatenate(rhs));
    }

    /**
     * Returns a parenthesized list of elements in this NEList.
     * Calls a helper method to ensure that there is no extra space before the
     * closing right parenthesis.
     */
    public String toString() {
        return "(" + _first + _rest.toStringHelp() + ")";
    }

    /**
     * This NEList is the rest of some other INEList.
     * Returns a space, followed by the toString() of _first, then followed
     * by the recursive toStringHelp() of _rest.
     * NOTE: The presence of the space String, " ", in the return expression
     * causes the compiler to call on _first.toString(), even though we only
     * write down _first.
     */
    public String toStringHelp() {
        return " " + _first + _rest.toStringHelp();
    }
}