0

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.

alex
  • 3
  • 1
  • not a queue, an array. queue is something different. – ItamarG3 Nov 06 '16 at 11:40
  • 1
    might be duplicate. check this link: http://stackoverflow.com/questions/5498865/size-limited-queue-that-holds-last-n-elements-in-java – OferP Nov 06 '16 at 11:42
  • `last100CleintList.add(client); last100CleintList.subList(0,100).clear()`. – Boris the Spider Nov 06 '16 at 11:46
  • 1
    You can do that with a circular buffer. Try googling for circular buffer + java. If you ever need something more general, go for a heap or an LRU. – Emanuel Landeholm Nov 06 '16 at 11:48
  • Are you sure you want to delete the last one and not the first one? Assuming that you always delete the last one everytime you add an element and you append to the list then the first 99 elements of the list will not change as you progress, but rather you will replace the last one everytime? – nmargaritis Nov 06 '16 at 11:49

1 Answers1

3

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
nmargaritis
  • 859
  • 7
  • 21