Creating a fixed-size Stack

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.


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

Tags:

Java

Stack