Why did they name PriorityQueue if you can\'t insertWithPriority? It seems very similar to a heap. Are there any differences? If no difference, the
From http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html
An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time
for integer, long, float, double, character, boolean (i.e. primitive data types) the natural ordering is ascending order, that's why Arrays.sort(arr) {where arr is an array of primitive data type} sorts the value of arr in ascending order. You can change the natural ordering by using a Comparator
Comparator can be used in two ways either
One of the way is how DpGeek showed
Another way is by using Anonymous Class. For example
Arrays.sort(arr, new Comparator() {
public int compare(Integer x, Integer y) {
return y - x;
}
});
Arrays.sort(arr, (Integer x, Integer y) -> y - x);
This sorts the array arr in descending order