64 lines
1.5 KiB
Java
64 lines
1.5 KiB
Java
package org.warp.commonutils.type;
|
|
|
|
import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet;
|
|
import org.warp.commonutils.error.IndexOutOfBoundsException;
|
|
|
|
public class FastUtilStackSetWrapper<T> implements StackSet<T> {
|
|
|
|
private final AddStrategy addStrategy;
|
|
private final ObjectLinkedOpenHashSet<T> linkedHashSet;
|
|
|
|
public FastUtilStackSetWrapper(ObjectLinkedOpenHashSet<T> linkedHashSet) {
|
|
this(linkedHashSet, AddStrategy.getDefault());
|
|
}
|
|
|
|
public FastUtilStackSetWrapper(ObjectLinkedOpenHashSet<T> 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();
|
|
}
|
|
}
|