list - Java Stack with elements limit -


i know question has asked many times after seaching hour still have problem.

i want use lifo stack has max number of elements can store.after reach max number deletes element @ first place , replace new in first pop can element , in second have element @ size-1.

what tried:

1) using modified stack ,as described here .the problem returning first 5 elements(if size 5) added.

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;     } } 

2)using arraydeque ,i dont see diference simple stack , not setting limit(am using wrong?)

arraydeque<state> lifo = new arraydeque<state>(5); lifo.pop(); lifo.push(state); 

i want use in puzzle game undo-redo functionality

solved: ended using fixed size stack tom said ,mainly performance

public class fixedstack<t> { private t[] stack; private int size; private int top; private int popbalance = 0;//its used see if 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; } }

i think efficient way fixed array, size equal max # of elements, , index points element 'top' of queue.

when add new element add @ index+1 (wrapping element 0 if necessary) , possibly overwriting element no longer fits. when pop element reverse.

this way data structure never has re-ordered, , can use array more light-weight collection.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -