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

前端 未结 6 1921
时光取名叫无心
时光取名叫无心 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:33

    From the PriorityQueue JavaDocs:

    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, depending on which constructor is used.

    Priority is meant to be an inherent property of the objects in the queue. The elements are ordered based on some sort of comparison. To insert some object with a given priority, you would just set whatever field(s) on the object affect the ordering, and add() it.


    And, as @Daniel commented,

    Generally Java Objects are named based on the functionality they provide, not named based on how they are implemented.

提交回复
热议问题