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:
import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class FixedList<T> { private final int size; private List<T> list; private Lock lock; public FixedList(int size) { list = new ArrayList<T>(); this.size = size; lock = new ReentrantLock(); } public T get(int index) { lock.lock(); try { return list.get(index); } finally { lock.unlock(); } } public void add(T element) { lock.lock(); try { while (list.size() >= size) { list.remove(list.size() - 1); } list.add(0, element); } finally { lock.unlock(); } } }
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
FixedList<Float> fixedList = new FixedList<>(10);
Leave a Reply