I want to create a Stack in Java, but fix the size. For example, create a new Stack, set the size to 10, then as I push items to the stack it fills up and when it fills up to ten, the last item in the stack is pushed off (removed). I want to use Stack because it uses LIFO and fits my needs very well.
But the setSize() method that Stack inherits from Vector doesn't seem to actually limit the size of the Stack. I think I am missing something about how Stacks work, or maybe Stacks weren't meant to be constrained so it is impossible. Please educate me!
Here is a
SizedStack
type that extendsStack
:Use it like this:
Stack<Double> mySizedStack = new SizedStack<Double>(10);
. Other than the size, it operates like any otherStack
.This is not impossible :) You just have to provide your own implementation.
I would start with a RingBuffer like this and adjust it accordingly.