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

143 lines
3.0 KiB
Java

package org.warp.commonutils.type;
import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet;
import java.util.Collection;
import org.jetbrains.annotations.NotNull;
import org.warp.commonutils.error.IndexOutOfBoundsException;
public class FastUtilStackSetWrapper<T> implements StackSet<T>, Collection<T> {
protected final AddStrategy addStrategy;
protected final ObjectLinkedOpenHashSet<T> linkedHashSet;
/**
* The first element will be the head
*/
public FastUtilStackSetWrapper(ObjectLinkedOpenHashSet<T> linkedHashSet) {
this(linkedHashSet, AddStrategy.getDefault());
}
/**
* The first element will be the head
*/
public FastUtilStackSetWrapper(ObjectLinkedOpenHashSet<T> linkedHashSet, AddStrategy addStrategy) {
this.addStrategy = addStrategy;
this.linkedHashSet = linkedHashSet;
}
@Override
public boolean push(T o) {
switch (addStrategy) {
case KEEP_POSITION:
if (linkedHashSet.contains(o)) {
return false;
}
return linkedHashSet.addAndMoveToFirst(o);
case OVERWRITE_POSITION:
return linkedHashSet.addAndMoveToFirst(o);
default:
throw new UnsupportedOperationException("Unsupported strategy type: " + addStrategy);
}
}
@NotNull
@Override
public java.util.Iterator<T> iterator() {
return linkedHashSet.iterator();
}
@NotNull
@Override
public Object @NotNull [] toArray() {
return linkedHashSet.toArray();
}
@NotNull
@Override
public <T1> T1 @NotNull [] toArray(@NotNull T1 @NotNull [] a) {
//noinspection SuspiciousToArrayCall
return linkedHashSet.toArray(a);
}
@Override
public boolean add(T t) {
return linkedHashSet.add(t);
}
@Override
public boolean remove(Object o) {
return linkedHashSet.remove(o);
}
@Override
public boolean containsAll(@NotNull Collection<?> c) {
return linkedHashSet.containsAll(c);
}
@Override
public boolean addAll(@NotNull Collection<? extends T> c) {
return linkedHashSet.addAll(c);
}
@Override
public boolean removeAll(@NotNull Collection<?> c) {
return linkedHashSet.removeAll(c);
}
@Override
public boolean retainAll(@NotNull Collection<?> c) {
return linkedHashSet.retainAll(c);
}
@Override
public void clear() {
linkedHashSet.clear();
}
@Override
public T pop() {
return linkedHashSet.removeFirst();
}
@Override
public int size() {
return linkedHashSet.size();
}
@Override
public boolean isEmpty() {
return linkedHashSet.isEmpty();
}
@Override
public boolean contains(Object o) {
return linkedHashSet.contains(o);
}
@Override
public T top() {
return linkedHashSet.first();
}
@Override
public T peek(int i) {
var size = linkedHashSet.size();
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException(i, 0, size);
}
var it = linkedHashSet.iterator();
// Skip middle elements
if (i > 0) {
it.skip(i);
}
return it.next();
}
@SuppressWarnings("MethodDoesntCallSuperMethod")
@Override
public FastUtilStackSetWrapper<T> clone() {
return new FastUtilStackSetWrapper<>(linkedHashSet.clone(), addStrategy);
}
}