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!
The maximum stack size is static because that is the definition of "maximum". Any sort of maximum on anything is a fixed, agreed-upon limiting figure. If it behaves as a spontaneously moving target, it isn't a maximum. Stacks on virtual-memory operating systems do in fact grow dynamically, up to the maximum.
Disadvantages of using Stack Memory in JavaStack memory is fixed and cannot grow or shrink once created.
size() method in Java is used to get the size of the Stack or the number of elements present in the Stack. Parameters: The method does not take any parameter. Return Value: The method returns the size or the number of elements present in the Stack.
1. Overview of Implement fixed size stack in Java. Stack is ADT type of data structure which has different implementation for different purpose for fulfilling of different contextual requirement. This article tried to implement how to implement by using fixed-size array-based implementation.
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
.
You can create a very simple stack like this:
public class FixedStack<T> { private T[] stack; private int size; private int top; public FixedStack<T>(int size) { this.stack = (T[]) new Object[size]; this.top = -1; this.size = size; } public void push(T obj) { if (top >= size) throw new IndexOutOfBoundsException("Stack size = " + size); stack[++top] = obj; } public T pop() { if (top < 0) throw new IndexOutOfBoundsException(); T obj = stack[top--]; stack[top + 1] = null; return obj; } public int size() { return size; } public int elements() { return top + 1; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With