package org.warp.commonutils.type; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; import org.warp.commonutils.error.IndexOutOfBoundsException; public class FastUtilStackSetWrapper implements StackSet { private final AddStrategy addStrategy; private final ObjectLinkedOpenHashSet linkedHashSet; public FastUtilStackSetWrapper(ObjectLinkedOpenHashSet linkedHashSet) { this(linkedHashSet, AddStrategy.getDefault()); } public FastUtilStackSetWrapper(ObjectLinkedOpenHashSet linkedHashSet, AddStrategy addStrategy) { this.addStrategy = addStrategy; this.linkedHashSet = linkedHashSet; } @Override public boolean push(T o) { switch (addStrategy) { case KEEP_POSITION: return linkedHashSet.add(o); case OVERWRITE_POSITION: return linkedHashSet.addAndMoveToLast(o); default: throw new UnsupportedOperationException("Unsupported strategy type: " + addStrategy); } } @Override public T pop() { return linkedHashSet.removeLast(); } @Override public boolean isEmpty() { return linkedHashSet.isEmpty(); } @Override public T top() { return linkedHashSet.last(); } @Override public T peek(int i) { var size = linkedHashSet.size(); int positionFromBottom = size - 1 - i; if (positionFromBottom < 0 || positionFromBottom >= size) { throw new IndexOutOfBoundsException(positionFromBottom, 0, size); } var it = linkedHashSet.iterator(); // Skip middle elements if (positionFromBottom > 0) { it.skip(positionFromBottom); } return it.next(); } }