When should I use a TreeMap over a PriorityQueue and vice versa?

后端 未结 8 2161
南旧
南旧 2020-12-23 11:46

Seems they both let you retrieve the minimum, which is what I need for Prim\'s algorithm, and force me to remove and reinsert a key to update its value. Is there any advanta

8条回答
  •  佛祖请我去吃肉
    2020-12-23 12:18

    There are 2 differences I would like to point out (and this may be more relevant to Difference between PriorityQueue and TreeSet in Java? as that question is deemed a dup of this question).

    (1) PriorityQueue can have duplicates where as TreeSet can NOT have dups. So in Treeset, if your comparator deems 2 elements as equal, TreeSet will keep only one of those 2 elements and throw away the other one.

    (2) TreeSet iterator traverses the collection in a sorted order, whereas PriorityQueue iterator does NOT traverse in sorted order. For PriorityQueue If you want to get the items in sorted order, you have to destroy the queue by calling remove() repeatedly.

    I am assuming that the discussion is limited to Java's implementation of these data structures.

提交回复
热议问题