Creating a fixed-size Stack

后端 未结 8 2370
执念已碎
执念已碎 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:51

    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 mySizedStack = new SizedStack(10);. Other than the size, it operates like any other Stack.

提交回复
热议问题