0

I have a hash map of a string and a vertex which is a class.

I want to create a priority queue for an attribute distance of vertex class... How should I do it...

private final PriorityQueue Nodes ;
private HashMap<String,Vertex> c ;

I have to create a priority queue on all the members of the hashmap c according to the vertex.distance value.....

Please tell how should i do that as I always get compilation error on whatever I am trying....

  • I am trying to get a priority queue which handles the vertex distances... As I have stored the vertices in hashmap I need to get this... –  Mar 19 '11 at 17:55
  • 1
    Take a look at http://stackoverflow.com/questions/683041/java-how-do-i-use-a-priorityqueue – JRL Mar 19 '11 at 17:56

2 Answers2

2

Without knowing your implementation, I give the following answer:

Looking at the javadoc, it appears that there is a constructor which accepts a Comparator. I suspect that what you need to do is create a comparator which corresponds to the vertex.distance value.

So, for example (this is untested code. Treat it as pseudo code):

class VertexComparator implements Comparator<Vertex>{
  public int compare(Vertex v1, Vertex v2){
    return v1.distance - v2.distance;
  }
}

After that create the Nodes like:

PriorityQueue Nodes = new PriorityQueue(100, new VertexComparator());
David Weiser
  • 5,190
  • 4
  • 28
  • 35
  • Just a question .... Where will I be using the hashmap in this ... as in inside the comparator function or just for passing inside the VertexComparator function.... –  Mar 19 '11 at 18:05
  • I'd get each vertex in the HashMap, and put the it in the Nodes PQ. But, it is hard for me to know because I do not know the problem you are trying to solve. – David Weiser Mar 19 '11 at 18:10
1

From what I understand of your question I think you want a PriorityQueue<Vertex>, which sorts instances of the Vertex class according to the value of its distance attribute.

What you need is to either define a Comparator that you pass in to the PriorityQueue which specifies how the objects are ordered, or you could make your Vertex class implement Comparable<Vertex> and implement its compareTo method.

MAK
  • 26,140
  • 11
  • 55
  • 86