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?
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.
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..!!
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 LinkedList
s are not optimized for random access).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With