Creating a fixed-size Stack

后端 未结 8 2371
执念已碎
执念已碎 2020-12-06 16:05

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

相关标签:
8条回答
  • 2020-12-06 16:43

    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.

    0 讨论(0)
  • 2020-12-06 16:48

    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).

    0 讨论(0)
  • 2020-12-06 16:51

    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.

    0 讨论(0)
  • 2020-12-06 16:51

    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.

    0 讨论(0)
  • 2020-12-06 16:52

    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.

    0 讨论(0)
  • 2020-12-06 16:54

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

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

    0 讨论(0)
提交回复
热议问题