common-utils/src/main/java/org/warp/commonutils/type/JavaStackSetWrapper.java

74 lines
1.5 KiB
Java

package org.warp.commonutils.type;
import java.util.LinkedHashSet;
import java.util.NoSuchElementException;
import org.warp.commonutils.error.IndexOutOfBoundsException;
public class JavaStackSetWrapper<T> implements StackSet<T> {
private final LinkedHashSet<T> linkedHashSet;
public JavaStackSetWrapper(LinkedHashSet<T> linkedHashSet) {
this.linkedHashSet = linkedHashSet;
}
@Override
public boolean push(T o) {
return linkedHashSet.add(o);
}
@Override
public T pop() {
var it = linkedHashSet.iterator();
if (!it.hasNext()) {
throw new NoSuchElementException();
}
// Go to the last element
T lastValue;
do {
lastValue = it.next();
} while (it.hasNext());
// Remove the last element
it.remove();
return lastValue;
}
@Override
public boolean isEmpty() {
return linkedHashSet.isEmpty();
}
@Override
public T top() {
if (linkedHashSet.isEmpty()) {
throw new NoSuchElementException();
}
var it = linkedHashSet.iterator();
T lastValue;
do {
lastValue = it.next();
} while (it.hasNext());
return lastValue;
}
@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) {
for (int j = 0; j < positionFromBottom; j++) {
it.next();
}
}
return it.next();
}
}