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:

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);

Comments

3 responses to “A List with a fixed size”

  1. ErwanLeroux Avatar
    ErwanLeroux

    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 ?

    1. 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.

      1. ErwanLeroux Avatar
        ErwanLeroux

        You’re welcome.

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.