0

I need to set the max size of a list to 10. For example, adding 10 elements like a normal list. but when adding more than 10 elements, instead of adding, i need to replace them.

Element 1
Element 2
Element 3
Element 4
Element 5
Element 6
Element 7
Element 8
Element 9
Element 10

Now when adding element 11, it should look like this:

Element 11
Element 2
Element 3
Element 4
Element 5
Element 6
Element 7
Element 8
Element 9
Element 10

Again, after adding another element to list:

Element 12
Element 11
Element 3
Element 4
Element 5
Element 6
Element 7
Element 8
Element 9
Element 10

How can i achieve this?
Thanks

Amirhossein
  • 179
  • 4
  • 18

2 Answers2

1

You could use a "Deque" (double-ended queue) instead of a list. This way, the FIFO logic is all handled for you by the data structure.

I haven't used them in Java but they seem to exist in Java 6+.

Another option: in this post, you can see a CircularFifoQueue<> that seems to do what you want.

samdouble
  • 452
  • 4
  • 12
1

How about making a custom wrapper around your list:

Kotlin:

class FiniteList<T>(private val size: Int) {
    private val list = mutableListOf<T>()

    fun add(item: T) {
        
        if (list.size < size) {
            list.add(item)
        } else {
            list.add(0, item)
            list.removeLast()
        }
        
    }
    
    //implement other methods

}

Java:

public class FiniteList<T> {
    private List<T> list;
    private int collectionSize;

    public FiniteListJava(int size) {
        collectionSize = size;
        new ArrayList<>(size);
    }

    void add(T item) {
        if (collectionSize > list.size()) {
            list.add(item);
        } else {
            list.add(0, item);
            list.remove(list.size() - 1);
        }
    }

    //implement other methods

}

Usage:

val finiteList = FiniteList<String>(10)
finiteList.add("Hello World!")
...
Arrowsome
  • 2,649
  • 3
  • 10
  • 35