title: Java Stack with elements limit
body: <p>I know this question has asked many times but  after seaching for an hour i still have problem.</p>
  
  <p>I want to use a lifo stack which has a max number of elements it can store.After it reach the max number is deletes the element at first place  and replace it with the new so in first pop i can get this element and in second i have to get the element at size-1.</p>
  
  <p>What i tried:</p>
  
  <p><strong>1)</strong> Using a modified Stack ,as described <a href="https://stackoverflow.com/questions/10359802/a-lifo-data-structure-that-holds-max-n-items">here</a> .The problem is that it always returning the first 5 elements(if the size is 5) i added.</p>
  
  <pre><code>class StackSizable&lt;E&gt; extends Stack&lt;E&gt;{
  
      int maxSize;
      StackSizable(int size)
      {
          super();
          this.maxSize=size;
      }
  
      @Override
      public E push(E elt) {
          super.push(elt);
          while (this.size() &gt; this.maxSize) {
              this.removeElementAt(this.size() - 1);
          }
          return null;
      }
  }
  </code></pre>
  
  <p><strong>2</strong>)Using an ArrayDeque ,i dont see any diference from a simple Stack , its not setting any limit(am i using it wrong?)</p>
  
  <pre><code>ArrayDeque&lt;State&gt; lifo = new ArrayDeque&lt;State&gt;(5);
  lifo.pop();
  lifo.push(state);
  </code></pre>
  
  <p>I want to use this in a puzzle game for undo-redo functionality</p>
  
  <p><strong>Solved:</strong> I ended using a fixed size stack as tom said ,mainly for the performance</p>
  
  <p><pre></p>
  
  <code>public class FixedStack&lt;T&gt; {
       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 &lt; size - 1)popBalance++;
       }
  
       public T pop() {
  
            if (top - 1 &lt; 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;
       }
  }
  </code></pre>