Which data structure can you advise to use in the following situation:
I use Java
I need smth like a stack – so last in first out, but a stack of fixed size, for example only 5 elements could be put inside, and when a new element is put onto the stack, the element at the bottom of the stack should be discarded, and I also want to get element by the index, that is the newest element has index 0 and the oldest element has index 4.
Is there smth appropriate in Java?
I’ve tried to use java.util.Stack, but for example if I set size to 3 and try to add 4 elements they all are added to the stack.
Java has ArrayDeque, which is basically a growable ring buffer. If you want to keep it at a fixed size, just check the size before pushing, and pop the bottom value if the size is too big.