/** * Constructs an empty LinkedList. */ public LinkedList() { this.first = null; this.rest = null; }
/** * Constructs a LinkedList containing only the given element. */ public LinkedList(Object _first) { this.first = _first; this.rest = null; }
/** * Constructs a LinkedList consisting of the given Object followed by * all the elements in the given LinkedList. */ public LinkedList(Object _first, LinkedList _rest) { this.first = _first; this.rest = _rest; } }
// If the objects are not of the same class, then they are not equal. // Reflection is used in case this method is called from an instance of a // subclass. if (this.getClass() == that.getClass()) {
/** * Constructs an empty LinkedList. */ public LinkedList() { this.value = new Empty(); }
/** * Constructs a LinkedList containing only the given element. */ public LinkedList(Object _first) { this.value = new Cons(_first); }
/** * Constructs a LinkedList consisting of the given Object followed by * all the elements in the given LinkedList. */ public LinkedList(Object _first, LinkedList _rest) { this.value = new Cons(_first, _rest.value); }
public Object getFirst() { return this.value.getFirst(); } public LinkedList getRest() { return new LinkedList(this.value.getRest()); } public void addFirst(Object o) { this.value = new Cons(o, this.value); } public boolean isEmpty() { return this.value instanceof Empty; }
public boolean equals(Object that) {
if (this.getClass() == that.getClass()) {
// The above test guarantees that the cast to LinkedList will always // succeed. return this.value.equals(((LinkedList)that).value); } else { return false; } } }
那时,执行一个不可变的链表是直截了当的,如清单 6 所示。
清单 6. 对节点作加法和乘法的方法
interface List { public Object getFirst(); public List getRest(); }
class Empty implements List { public Object getFirst() { throw new NoSuchElementException(); } public List getRest() { throw new NoSuchElementException(); } public boolean equals(Object that) { return this.getClass() == that.getClass(); } }
class Cons implements List {
Object first; List rest;
Cons(Object _first) { this.first = _first; this.rest = new Empty(); } Cons(Object _first, List _rest) { this.first = _first; this.rest = _rest; } public Object getFirst() { return this.first; } public List getRest() { return this.rest; }
public boolean equals(Object that) { if (this.getClass() == that.getClass()) {
// The above test guarantees that the cast to Cons will always succeed. Cons _that = (Cons)that;