views:

44

answers:

3

Hello,

Can I use Collections.binarySearch() method to search elements in a PriorityQueue? Otherwise, how can I apply search algorithms to a PriorityQueue?

I have this (class Evento implements Comparable):

    public class PriorityQueueCAP extends PriorityQueue<Evento>{

       // (...)

       public void removeEventos(Evento evento){

           Collections.binarySearch(this, evento); // ERROR!

       }
    }

And I got this error: "The method binarySearch(List>, T) in the type Collections is not applicable for the arguments (PriorityQueueCAP, Evento)"

Why?

Thanks in advance!

+3  A: 

You should not apply a search algorithm to a priority queue. A priority queue is designed to provide efficient access to the highest priority element in the collection, and that is all.

I know that this is probably not the answer for which you were hoping; I've seen too many problems arise from using tools for unintended purposes, and felt I should offer a word of warning.

erickson
"A priority queue is designed to provide efficient access to the highest priority element in the collection". Im using it with that purpose. However I also need to find elements in an efficient manner. How can I accomplish that?
msr
The most efficient method for searching a heap would be an O(n) examination of each element returned by its iterator.
erickson
That's what Im using. But it seems to take long time since I have to do that very frenquently and the priorityqueue size is around 5000 (or greater).
msr
Right. That's the best you can hope for if you stick with priority queue. Have you considered, instead of removing objects from the queue, flagging the object as "cancelled" or "ignorable"? That way, you don't have to go digging around in the queue contents, but just wait until it comes up and throw it away without processing.
erickson
A: 

This tutorial shows you how to initiate a collection and the possible operations you can perform on it. You should keep in mind what erickson said.

npinti
+1  A: 

What exactly do you need the binary search for? Your code implies that you want to use it for removing items from the priority queue. The priority queue already has the remove(item) method, and it works in O(log n) time.

If on the other hand you need a binary search just to check for existence of some item, then the PriorityQueue.contains() method can help, though it is not very efficient (it takes linear time). You should consider a TreeSet instead.

Eyal Schneider