bernie2436
bernie2436

Reputation: 23901

How do I get the nth item in a 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?

Upvotes: 7

Views: 36428

Answers (5)

Mark Peters
Mark Peters

Reputation: 81074

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).

Upvotes: 2

Hauke Ingmar Schmidt
Hauke Ingmar Schmidt

Reputation: 11607

Queues don't allow random, indexed access by concept so it is a good thing that the interface does not allow this either. If you need both kinds of access at the same time (which is a bad sign for design) then you could use a datatype that implements both List and Queue (e.g. LinkedList).

Upvotes: 1

Cratylus
Cratylus

Reputation: 54074

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

What concrete data type are you using for Queues? A LinkedList?In this case you should be able to get the nth element by casting back to linked list.

But this is not how you would use a Queue

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

Priority Queue will always return the min element (by ordering).
So what do you mean the n element here?The n smallest or the n inserted or what? So we can't really say what to do in this case

Upvotes: 1

Ramandeep Singh
Ramandeep Singh

Reputation: 5253

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..!!

Upvotes: 2

Michael Borgwardt
Michael Borgwardt

Reputation: 346300

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.

Upvotes: 20

Related Questions