You could do it in the way that you have described but the performance of such a List would be low. Imagine that the limit has been reached and you remove the first element. Under the hood this would involve copying all elements of the underlying array one index up. Then the new element is added to the last index. Especially the copying of all elements is costly
Alternatively you could use a LinkedList
, which is more efficient for these kind of operations.
Another way would be to write you own class to implement a Circular Buffer.
This is basically an array of size MAX. You have to keep an index of the first element and the number of elements in the array. When you add an element, you check whether the number of elements equals MAX, if so, you overwrite the first element and increase the index of the first element by one.
Indexed getters and setters need to take into account the offset of the first element as well, but this is not overly complicated.
The best choice depends on your use case. If you have to do a lot of inserts and deletes at random places in the list, LinkedList
is definitely the way to go. If you only want to add items to the end and removing the head, the circular buffer is very efficient.