2

Possible Duplicate:
Size-limited queue that holds last N elements in Java

Does java include a native class which allows a maximum number of elements and if I input one element more, it automatically removes an old one (e.g. based on natural sorting)?

If not, I can write it myself of course, but I just wanted to ask.

Community
  • 1
  • 1
aufziehvogel
  • 7,167
  • 5
  • 34
  • 56
  • Your answer in this edited question: [ffriend's Question](http://stackoverflow.com/questions/7878026/is-there-a-priorityqueue-implementation-with-fixed-capacity-and-custom-comparato) – waldyr.ar Jul 20 '12 at 15:38

1 Answers1

6

There are lots.

You can use a Queue, and specify a fixed length. Implement your own using an ArrayList that removes element 0 every time a new element is added that increases the size past your limit.

A popular technique is to make a queue with a LinkedHashMap

  queue = new LinkedHashMap<Integer, String>()
  {
     @Override
     protected boolean removeEldestEntry(Entry<Integer, String> eldest)
     {
        return this.size() > yourMaxSize;   
     }
  };
Rob Wagner
  • 4,391
  • 15
  • 24