user506710
user506710

Reputation:

Priority queue for HashMaps

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

Upvotes: 0

Views: 8182

Answers (2)

MAK
MAK

Reputation: 26586

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.

Upvotes: 1

David Weiser
David Weiser

Reputation: 5205

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());

Upvotes: 2

Related Questions