/** * Data Definition: IntList := new Empty() + new Cons(int, IntList) */ abstract class IntList { /** * throws an IllegalArgumentException on Empty * returns first element of non-empty list */ abstract int getFirst(); /** * given the elements of this appear in non-descendin order * returns this with e inserted in nonde */ abstract IntList getRest(); abstract String toStringHelp(); abstract int sum(); abstract int sumHelp(int acc); abstract void findNeg(ICommand c); } /** * 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 Empty extends IntList { /** * Singleton pattern. */ public static Empty only = new Empty(); private Empty() {} int getFirst() { throw new IllegalArgumentException("An Empty IntList has no first."); } IntList 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; } void findNeg(ICommand c) {} } /** * Represents a non-empty list. * Note the use of the toStringHelp() "helper" method to "help" compute the * String representation of the rest. */ class Cons extends IntList { int first; IntList rest; Cons(int f, IntList r) { first = f; rest = r; } int getFirst() { return first; } IntList 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(first); } int sumHelp(int acc){ return rest.sumHelp(acc + first); } void findNeg(ICommand c) { if(first < 0) { c.apply(first); } else { rest.findNeg(c); } } }