Cal*_*vin 24
这是一种SizedStack
扩展的类型Stack
:
import java.util.Stack;
public class SizedStack<T> extends Stack<T> {
private int maxSize;
public SizedStack(int size) {
super();
this.maxSize = size;
}
@Override
public T push(T object) {
//If the stack is too big, remove elements until it's the right size.
while (this.size() >= maxSize) {
this.remove(0);
}
return super.push(object);
}
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它:Stack<Double> mySizedStack = new SizedStack<Double>(10);
.除了尺寸,它的运作方式与其他任何一样Stack
.
您可以创建一个非常简单的堆栈,如下所示:
public class FixedStack<T>
{
private T[] stack;
private int size;
private int top;
public FixedStack<T>(int size)
{
this.stack = (T[]) new Object[size];
this.top = -1;
this.size = size;
}
public void push(T obj)
{
if (top >= size)
throw new IndexOutOfBoundsException("Stack size = " + size);
stack[++top] = obj;
}
public T pop()
{
if (top < 0) throw new IndexOutOfBoundsException();
T obj = stack[top--];
stack[top + 1] = null;
return obj;
}
public int size()
{
return size;
}
public int elements()
{
return top + 1;
}
}
Run Code Online (Sandbox Code Playgroud)