How does Java's PriorityQueue differ from a min-heap?

前端 未结 6 2057
时光取名叫无心
时光取名叫无心 2021-01-30 00:44

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

6条回答
  •  忘掉有多难
    2021-01-30 01:31

    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;
         }
    });
    
    • If you have java8 then you can use the lambda expression

    Arrays.sort(arr, (Integer x, Integer y) -> y - x);

    This sorts the array arr in descending order

提交回复
热议问题