Difference Between PriorityQueue and TreeSet
The PriorityQueue and TreeSet both are the classes defined inside the Collection Framework. In this article, we will learn the differences between PriorityQueue and TreeSet. PriorityQueue is an implementation of Queue interface and the TreeSet is the implementation of the Set interface. There are some differences exists between them. So we have tried to list out the differences between PriorityQueue and TreeSet.
1. PriorityQueue: A PriorityQueue is used when the objects are supposed to be processed based on the priority. It is known that a Queue follows the First-In-First-Out algorithm, but sometimes the elements of the queue are needed to be processed according to the priority, that’s when the PriorityQueue comes into play. The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered according to the natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used.
For For Geeks
2. TreeSet: TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class.
Differences between PriorityQueue and TreeSet
|PriorityQueue uses the Queue underlying data structure||TreeSet uses the Set underlying data structure.|
|PriorityQueue allows the duplicate elements||TreeSet doesn’t allow the duplicate elements|
|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.||TreeSet doesn’t provide a way to retrieve largest or smallest element in O(1) time, but since they are in sorted order it gets the first or last element in O(1) time.|
|PriorityQueue comes in JDK 1.5.||TreeSet comes in JDK 1.4.|