How can I get the nth item in the queue?

I have several queues and priority queues in my application. I would like to easily access the nth elements in these queues, but I see no easy way to do this using the API.

I think I could create an Iterator and go to the nth element or use toArray()[index] , but there seems to be an easier way.

Did I miss something?

+5
source share
5 answers

Did I miss something?

Yes - the fact that accessing items by index is not part of the concept of a queue.

If you need to access elements by index, you need a list, not qeue.

+17
source

The whole point of the queue is to open access only to the head (the first element). If you need random access to elements in a linear data structure, use List (if you are doing much more searches than push / pops, consider using ArrayList , since LinkedList not optimized for random access).

+2
source

The simplest solution for you is to use a binary search tree , which is self-balancing, for example. AVL tree, splay tree or red-black tree . It allows you to access elements by their key in O (log n) and iterate objects in order in O (log n + k) , where k is the number of iteration elements .. !!

+2
source

I have the number of priority and priority queues in my application

What specific data type do you use for Queues ? A LinkedList ? In this case, you should get the element n th, returning it to the linked list.

But you should not use Queue

Regarding the priority queue, it seems from your question that you are also not using the correct data structures.

The priority queue always returns the min element (optional).
So what do you mean here element n ? Insertable n or n inserted or what? Therefore, we cannot say what to do in this case.

+1
source

Queues do not allow random, indexed access by concept, so it’s good that the interface does not allow this. If you need both types of access at the same time (this is a bad sign for design), you can use a data type that implements both List and Queue (for example, LinkedList ).

+1
source

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


All Articles