lundi 15 juin 2015

Issue instantiating an immutable implementation of a stack

I am slightly stuck trying to implement the composite pattern on a stack.

I have an EmptyStack implementation

public final class EmptyStack<E> implements IImmutableStack<E> {

    public IImmutableStack<E> pop() { return null; }
    public IImmutableStack<E> push(E value) { return new Stack<E>(value, this); }
    public E peek() { return null; }
    public int getSize() { return 0; }
    public boolean isEmpty() { return true; }

}

And the NonEmptyStack

public final class Stack<E> implements IImmutableStack<E> {

    private final E head;
    private final IImmutableStack<E> tail;

    public Stack (E head, IImmutableStack<E> tail) {
        this.head = head;
        this.tail = tail;
    }

    public static <E> IImmutableStack<E> empty(final Class<E> type) {
        return new EmptyStack<E>();
    }

    public IImmutableStack<E> pop() { return this.tail; }
    public IImmutableStack<E> push(E e) { return new Stack<E>(e, this); }
    public E peek() { return this.head; }
    public boolean isEmpty() { return (head == null && tail == null); }
    public int getSize() { return isEmpty() ? 0 :  1 + tail.getSize(); }
}

I am trying to instantiate it with a Gen object type without luck. This is my failed attempt - how can I instantiate it correctly?

private final IImmutableStack<Node<K,E>> stack = Stack.empty(Node<K,E>);

Aucun commentaire:

Enregistrer un commentaire