alex alex - 26 days ago 6
Java Question

Create a java List with maximum of 100 values

I create a list of object with java

public class Cleint {

private int id;
private String user;
private int age;

public static List<Client> last100CleintList;


The list is supposed to be a kind of queue where the last 100 clients are stored. So when the list is empty I just want to add clients but when I reach 100 I want to delete the last one and add the new one. I could do it manually but is there a function for that? Or maybe in arrays, I am not forced to use lists.

Answer

There is no built-in library to achieve that (data-structure is there) without creating a utility method yourself.

Since you want to keep the last 100Clients every-time you append; and the list size is 100, you have to remove the first Client. You could try something like this (with Client objects).

    import java.util.Queue;
    import org.apache.commons.collections4.queue.CircularFifoQueue;`

    Queue<String> circularQueue = new CircularFifoQueue<String>(2);
    circularQueue.add("Bob");
    circularQueue.add("Doe");
    circularQueue.add("Joe");

then

System.out.println(circularQueue);

outputs ["Doe", "Joe"];

You can also do this with:

  1. com.google.common.collect.EvictingQueue
  2. MinMaxPriorityQueue by guava
Comments