I have priority queue in Java of Integers:
PriorityQueue pq= new PriorityQueue();
When I call pq.poll(
The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time.
The Comparator should override the compare method.
int compare(T o1, T o2)
Default compare method returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
The Default PriorityQueue provided by Java is Min-Heap, If you want a max heap following is the code
public class Sample {
public static void main(String[] args) {
PriorityQueue q = new PriorityQueue(new Comparator() {
public int compare(Integer lhs, Integer rhs) {
if(lhsrhs) return -1;
return 0;
}
});
q.add(13);
q.add(4);q.add(14);q.add(-4);q.add(1);
while (!q.isEmpty()) {
System.out.println(q.poll());
}
}
}
Reference :https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#comparator()