I think what you want is (almost) already available in libraries: LinkedHashSet is a hash set with a basic doubly linked list (which makes it iterable). LinkedHashMap even has removeEldestEntry, which sounds very similar to the pop method.
How a naive solution works like:
class HashStack<T> {
private HashMap<T, Integer> counts = new HashMap<T, Integer>(); private Stack<T> stack = new Stack<T>(); public void push(T t) { stack.push(t); counts.put(t, 1 + getCount(t)); } public T pop() { T t = stack.pop(); counts.put(t, counts.get(t) - 1); return t; } private int getCount(T t) { return counts.containsKey(t) ? counts.get(t) : 0; } public boolean contains(T t) { return getCount(t) > 0; } public String toString() { return stack.toString(); } }
source share