package stack;

public abstract class AbstractStack<E> implements Stack<E>, Cloneable {

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof AbstractStack) {
			AbstractStack<E> stack = (AbstractStack<E>) obj;
			Stack<E> objCopy = null;
			Stack<E> thisCopy = null;
			try {
				objCopy = (Stack<E>) stack.clone();
				thisCopy = (Stack<E>) this.clone();
				while (!thisCopy.isEmpty() && !objCopy.isEmpty()) {
					if (!thisCopy.peek().equals(objCopy.peek())) {
						return false;
					}
					thisCopy.pop();
					objCopy.pop();
				}
			} catch (CloneNotSupportedException | EmptyStackException e) {
				e.printStackTrace();
				return false;
			}
			return thisCopy.isEmpty() && objCopy.isEmpty();
		}
		return false;
	}

	@Override
	public String toString() {
		String s = "[";
		Stack<E> clone = null;
		try {
			clone = (Stack<E>) this.clone();
			while (!clone.isEmpty()) {
				s += clone.peek();
				clone.pop();
				if (!clone.isEmpty())
					s += ", ";
			}
		} catch (CloneNotSupportedException | EmptyStackException e) {
			e.printStackTrace();
			return null;
		}
		s += "]";
		return s;
	}

}
