Creating a fixed-size Stack

2020-02-01 06:44发布

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!

标签: java stack
8条回答
戒情不戒烟
2楼-- · 2020-02-01 07:22

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.

查看更多
等我变得足够好
3楼-- · 2020-02-01 07:28

This is not impossible :) You just have to provide your own implementation.

I would start with a RingBuffer like this and adjust it accordingly.

查看更多
登录 后发表回答