/** Composite representation of IntList ::= EmptyIntList | ConsIntList(int, IntList) with visitor interface. * The interface is defined in a different file. */ abstract class IntList { abstract Object accept(IntListVisitor v); /** Sorts this IntList into ascending (non-descending) order. */ abstract IntList sort(); /** Adds the int n to the front of this IntList. */ IntList cons(int n) { return new ConsIntList(n, this); } /** Inserts n in proper order in this IntList, assuming this is sorted in ascending order. */ abstract IntList insert(int n); } class EmptyIntList extends IntList { /** Field containing the only (singleton) EmptyIntList. */ static EmptyIntList ONLY = new EmptyIntList(); /** Constructor used to create ONLY. */ private EmptyIntList() { } Object accept(IntListVisitor v) { return v.forEmptyIntList(this); } IntList sort() { return this; } IntList insert(int n) { return cons(n); } } class ConsIntList extends IntList { /** The first element of this. */ int first; /** The remaining elements of this. */ IntList rest; Object accept(IntListVisitor v) { return v.forConsIntList(this); } IntList sort() { return rest.sort().insert(first); } IntList insert(int n) { if (n <= first) return cons(n); else return rest.insert(n).cons(first); } }