Creating a fixed-size Stack

后端 未结 8 2372
执念已碎
执念已碎 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 17:03

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 17:05

    You can use LinkedHashMap and override its removeEldestEntry method:

    public class FixedStack extends LinkedHashMap<Long, String> {
    
        private final int capacity;
    
        public FixedStack(int capacity) {
            this.capacity = capacity;
        }
    
        @Override
        protected boolean removeEldestEntry(final Map.Entry<Long, String> eldest) {
            return super.size() > capacity;
        }
    }
    

    And to test it:

        public static void main(String[] args) {
    
            FixedStack stack = new FixedStack(10);
    
            long added = 0;
            for (Locale locale : Locale.getAvailableLocales()) {
                if (locale.getDisplayCountry().length() > 0) {
                    stack.put(added, locale.getDisplayCountry());
                    System.out.println(locale.getDisplayCountry());
                    added++;
                }
            }
            System.out.println(String.format(">>>>>>>>> %s added",
                    added));
            Iterator<Entry<Long, String>> iterator = stack.entrySet().iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next().getValue());
            }
        }
    

    You just have to decide what you want to use as the key, I used a simple counter in the example.

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