0

I am tracking a list of colors. I only need to worry about the last two colors added to this list. So this queue should be a fixed size (of 2).

    queue.add(color1);
    queue.add(color2);
    queue.add(color3); //adding color3 should automatically remove color1 from the queue. 
    //So the queue should now only contain 'color2' and 'color3'

Does Java have a built in Collection for this type of operation? Or do I need to build it myself?

ZakTaccardi
  • 12,212
  • 15
  • 59
  • 107
  • It should be simple enough to implement. You could just extend some existing implementation and override `add` method to handle removing the head. No additional dependencies required. – lared Feb 13 '15 at 15:03
  • 1
    This question is already answered. http://stackoverflow.com/questions/5498865/size-limited-queue-that-holds-last-n-elements-in-java – Mahesh Acharya Feb 13 '15 at 15:05

1 Answers1

1

I think you're probably looking for the CircularFifoQueue from Apache Commons 4.x, which has a fixed size and silently removes elements to make room for new elements. This is from the doc:

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.

The removal order of a CircularFifoQueue is based on the insertion order; elements are removed in the same order in which they were added. The iteration order is the same as the removal order.

Community
  • 1
  • 1
HavelTheGreat
  • 3,299
  • 2
  • 15
  • 34
  • Awesome, thanks! I am going to use `EvictingQueue` from the Guava library, which seems to do the same thing. I will accept this answer though as it pointed me in the right direction! http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/collect/EvictingQueue.html – ZakTaccardi Feb 13 '15 at 15:06