/** * Data Definition: IntList := new Empty() + new Cons(int, IntList) */ abstract class AObjList { /** * throws an IllegalArgumentException on Empty * returns first element of non-empty list */ abstract Object getFirst(); /** * given the elements of this appear in non-descendin order * returns this with e inserted in nonde */ abstract AObjList getRest(); abstract String toStringHelp(); abstract int sum(); abstract int sumHelp(int acc); } /** * Represents the unique empty list using the singleton pattern. * This is also an example of the Null Object pattern. * Note the use of exceptions to express programming errors in getFirst() and * getRest(). */ class EmptyObjList extends AObjList { /** * Singleton pattern. */ public static EmptyObjList only = new EmptyObjList(); private EmptyObjList() {} Object getFirst() { throw new IllegalArgumentException("An Empty IntList has no first."); } AObjList getRest() { throw new IllegalArgumentException("An Empty IntList has no rest."); } public String toString() { return "()"; } String toStringHelp() { return ""; } int sum(){ return 0; } int sumHelp(int acc){ return acc; } } /** * Represents a non-empty list. * Note the use of the toStringHelp() "helper" method to "help" compute the * String representation of the rest. */ class ConsObj extends AObjList { Object first; private AObjList rest; ConsObj(Object f, AObjList r) { first = f; rest = r; } Object getFirst() { return first; } AObjList getRest() { return rest; } /** * no leading space before first */ public String toString() { return "(" + first + rest.toStringHelp() + ")"; } /** * leading space before each elt */ String toStringHelp() { return " " + first + rest.toStringHelp(); } int sum(){ return rest.sumHelp( ((Integer)first).intValue() ); } int sumHelp(int acc){ return rest.sumHelp(acc + ((Integer)first).intValue()); } }