Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the nth item in a Queue?

Tags:

java

queue

I have a number of queues and priority queues in my application. I would like to easily access the nth items in these queues, but don't see an easy way to do that using the API.

I guess I could create an Iterator and iterate to the nth element or use toArray()[index], but it seems like there should be an easier way.

Am I missing something?

like image 727
bernie2436 Avatar asked Mar 09 '12 16:03

bernie2436


3 Answers

Am I missing something?

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

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

like image 165
Michael Borgwardt Avatar answered Nov 16 '22 01:11

Michael Borgwardt


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

like image 35
Ramandeep Singh Avatar answered Nov 16 '22 01:11

Ramandeep Singh


The entire point of a queue is to expose access only to the head (the first element). If you want arbitrary access to elements in a linear data structure, use a List (if you're doing a lot more lookups than push/pops, consider using an ArrayList as LinkedLists are not optimized for random access).

like image 2
Mark Peters Avatar answered Nov 16 '22 01:11

Mark Peters