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 t
What you need is a double-ended queue like LinkedList
. This wouldn't automatically drop elements at the front though, but by subclassing/decorating it you could add that functionality.
You can subclass Stack
and override the appropriate method(s) to implement this custom behavior. And make sure to give it a clear name (e.g. FixedStack
).
Here is a SizedStack
type that extends 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);
}
}
Use it like this: Stack<Double> mySizedStack = new SizedStack<Double>(10);
. Other than the size, it operates like any other Stack
.
A LinkedBlockingDeque
is one simple option. Use the LinkedBlockingQueue(int) constructor where the parameter is the your stack limit.
As you observed, Stack
and Vector
model unbounded sequences. The setSize()
method truncates the stack / vector. It doesn't stop the data structure from growing beyond that size.
A pure stack would not limit its size, as for many of the problems stacks solve you don't know how many elements you are going to need.
You could write a custom stack that implements the needs you described. However, you will break LIFO if you do. If the max size is met, and you push something new on the stack, you just lose the previously added item. So if you then start popping items off your stack, you'll miss some.
This is not impossible :) You just have to provide your own implementation.
I would start with a RingBuffer like this and adjust it accordingly.