Ok so I'm trying to use a java priority queue to sort nodes by the double val they contain. I know how to do a priority queue by double but I need the rest of the node values for a huffman encoding tree construction. Is there a way to sort a priority queue of nodes by their val or would I be better off making the queue sort the double vals and then trying to match them to the nodes?
You have two options, and the choice depends on what the Double means in the Node:
Node implement Comparable<Node>, and use PriorityQueue<Node>. The compareTo method will order by the Double. The queue order you want is the natural order of the elements.PriorityQueue constructor that takes a Comparator argument. The Comparator you use for the queue should order according to the Double value.The first one is better if the Double really is the natural order for the nodes. The second one is better if it is only important for this queue, and other fields are equally important for other purposes.
You can use PriorityQueue<Node> implementation and manage the ordering of elements by overriding compare method of the Comparator interface during the queue construction time.
For example: To sort elements in ascending order of their Node values, use the below-mentioned declaration of the priority queue and then simply add nodes to the priority queue.
PriorityQueue<Node> pq = new PriorityQueue<Node>(new Comparator<Node>(){
public int compare(Node node1, Node node2){
if(node2.val>node1.val){
return -1;
}
else{
return 1;
}
}
});