我知道這個問題已經詢問了很多次,但在一小時後我仍然有問題。具有元素限制的Java堆棧
我想要使用一個lifo棧,它有最大數量的元素它可以存儲。達到最大數量後刪除該元素在第一個地方,並替換爲新的,所以在第一個彈出我可以得到這個元素在第二個我必須得到大小爲1的元素。
我的嘗試:
1)使用修改的堆棧,如所描述here。問題是,它總是返回第一5個元素(如果大小爲5)1加入。
class StackSizable<E> extends Stack<E>{
int maxSize;
StackSizable(int size)
{
super();
this.maxSize=size;
}
@Override
public E push(E elt) {
super.push(elt);
while (this.size() > this.maxSize) {
this.removeElementAt(this.size() - 1);
}
return null;
}
}
)使用ArrayDeque,我沒有看到,從一個簡單的堆棧中的任何性差異,它不設置任何限制(我使用它錯了嗎?)
ArrayDeque<State> lifo = new ArrayDeque<State>(5);
lifo.pop();
lifo.push(state);
我想用這個在益智遊戲撤消,重做功能
解決:我使用一個固定大小的堆棧湯姆結束說,主要是針對性能
public class FixedStack<T> {
private T[] stack;
private int size;
private int top;
private int popBalance = 0;//its used to see if all the elements have been popped
public FixedStack(T[] stack) {
this.stack = stack;
this.top = 0;
this.size = stack.length;
}
public void push(T obj) {
if (top == stack.length)top = 0;
stack[top] = obj;
top++;
if (popBalance < size - 1)popBalance++;
}
public T pop() {
if (top - 1 < 0)top = size;
top--;
T ob = stack[top];
popBalance--;
return ob;
}
public void clear() {
top = 0;
}
public int size() {
return size;
}
public boolean poppedAll() {
if (popBalance == -1)return true;
return false;
}
}
看看這個:http://stackoverflow.com/questions/7727919/creating-a-fixed-size-stack – 2013-04-05 18:02:13
@JerryAndrews除非他想要的東西,刪除當它達到容量的第一要素,所以我認爲像那個,但是包裝更好(下面加入)。 – Tom 2013-04-05 18:18:30