A List with a fixed size

There isn’t a class that extends List for which you can set a limit on its size and that it behaves like a Queue object if you add an item beyond its fixed size.

In other words, I need a class that

  • behaves as a List, in particular with a “get” method with an index, such as ArrayList
  • with a maximum number of elements, beyond which, if you add other elements, the class behaves like a queue with a FIFO logic (first-in first-out)

The following code is a possible solution:

The argument of the constructor is an integer that sets the size of the List and can not be changed, the class that implements List is initialized in the constructor and in this case is an ArrayList.
The get(int index) method returns the object at position index without removing it, the add(T element) method adds the object at the head of the list if necessary removing an object from the tail in order to have no more than size elements.

For example, the code to create an object for 10 Float is

3 replies on “A List with a fixed size”

What is the purpose of getList() and setList(List list) methods ? I’m asking this because you can change the size of the underlaying list using setList(List list). Kinda defeat the purpose of the whole class no ?

I think your argument is correct, the getter and setter methods for the list are dangerous, it is best to avoid a direct access to the inner list.
I corrected the post.
Thank you very much for your comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.