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
Here is a SizedStack
type that extends Stack
:
import java.util.Stack;
public class SizedStack extends Stack {
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
. Other than the size, it operates like any other Stack
.