Java, a collection for a known number of listings

which collection should I use if:

  • I want to save max. 5 Enums in collection
  • Reading, writing, and iterating over a collection can occur several times per second
  • If I need to add a new element, the oldest element will be deleted (suppose it has e1...e5 , and when I add e6 , it will be e2...e6 ).

I will almost always iterate over the entire collection. I think LinkedList is what I need, but I'm not very experienced in Java , so I want to make sure.

+4
source share
3 answers

LinkedBlockingQueue

 LinkedBlockingQueue lbq =new LinkedBlockingQueue(5); if(!(lbq.offer(newOBject)){ lbq.take(); lbq.offer(newObject); } 

EnumMap can also be useful, keys are limited to enumeration instances.

+2
source

Here you need a queue data structure that supports FIFO.

You can use the LinkedList from the Collections Framework. It implements a queue interface.

Learn more about Linked List in Java .

+1
source

If you do not need to force the use of queue capacity , you can simply use LinkedList . It implements the Queue interface that you really need.

Use it as follows:

 Queue<EnumClass> queue = new LinkedList<EnumClass>(); queue.offer(newObj); takenObj = queue.poll(); 

If you need to limit the size , then ArrayBlockingQueue would be a good option, since there would be no additional creation of an internal object (collection supported by the array).

 Queue<EnumClass> queue = new ArrayBlockingQueue<EnumClass>(capacity); 

However, using it with the Queue interface would be a good idea. This way you can change the actual implementations as you wish.

0
source

Source: https://habr.com/ru/post/1500681/


All Articles