Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between PriorityQueue and TreeSet in Java? [duplicate]

I am trying to understand when to use the two data structures. As far as I have understood the PriorityQueue is also implemented as a tree as the documentation states that the average time for insert, remove and contains is O(log(n)). The TreeSet also provides the same time complexity. Plus both of them are unsynchorized implementation. And I can write comparator for them to act like min heap or max heap.

Can some one point out in what conditions I use these two sets?

like image 886
Fox Avatar asked May 10 '13 17:05

Fox


People also ask

Does PriorityQueue allow duplicates?

Answer: Yes. Priority Queue allows duplicate values.

What is the difference between PriorityQueue and TreeSet in Java?

Differences between PriorityQueue and TreeSetTreeSet uses the Set underlying data structure. In PriorityQueue, apart from the root rest of the elements may or may not follow any order. In TreeSet all the elements remain in the sorted order. Using PriorityQueue, we can retrieve largest or smallest element in O(1) time.

Can Java TreeSet have duplicates?

TreeSet cannot contain duplicate elements. The elements in a TreeSet are sorted as per their natural ordering, or based on a custom Comparator that is supplied at the time of creation of the TreeSet. TreeSet cannot contain null value.

How does priority queue handle duplicates?

A PriorityQueue in Java does not have any restriction with regard to duplicate elements. If you want to ensure that two identical items are never present in the priority queue at the same time the simplest way would be to maintain a separate Set in parallel with the priority queue.


1 Answers

When you want a queue, use a PriorityQueue. When you want a Set, use a TreeSet. A TreeSet has unique elements, and doesn't offer the API of a Queue. A Queue doesn't offer the API of a Set, and allows multiple equal elements.

like image 67
JB Nizet Avatar answered Sep 27 '22 09:09

JB Nizet