Both PriorityQueue and TreeSet are implementations of the Set interface in Java, but they have some differences in terms of their underlying data structures and the ordering of elements.
Data structure:
PriorityQueue: It uses a binary heap data structure to store its elements. The elements in a PriorityQueue are ordered based on their natural ordering or a custom comparator.
TreeSet: It internally uses a self-balancing binary search tree, specifically a red-black tree, to store its elements. The elements in a TreeSet are ordered based on their natural ordering or a custom comparator.
Ordering of elements:
PriorityQueue: Elements in a PriorityQueue are ordered based on their priority. The priority can be determined either by the natural ordering of the elements or by a custom comparator. The element with the highest priority will be at the head of the queue.
TreeSet: Elements in a TreeSet are ordered in a sorted manner. They are stored in a specific order defined by their natural ordering or a custom comparator. The elements are sorted in ascending order by default.
Duplicates:
PriorityQueue: It allows duplicate elements. Elements with the same priority can exist in a PriorityQueue.
TreeSet: It does not allow duplicate elements. Any attempt to add a duplicate element to a TreeSet will be ignored. Here's an example to demonstrate the differences:
import java.util.PriorityQueue;
import java.util.TreeSet;
public class SetExample {
public static void main(String[] args) {
// PriorityQueue example
PriorityQueue priorityQueue = new PriorityQueue<>();
priorityQueue.add(10);
priorityQueue.add(5);
priorityQueue.add(15);
priorityQueue.add(5); // Duplicate element
System.out.println("PriorityQueue: " + priorityQueue);
// Output: PriorityQueue: [5, 5, 15, 10]
// TreeSet example
TreeSet treeSet = new TreeSet<>();
treeSet.add(10);
treeSet.add(5);
treeSet.add(15);
treeSet.add(5); // Duplicate element (ignored)
System.out.println("TreeSet: " + treeSet);
// Output: TreeSet: [5, 10, 15]
}
}
In this example, we create a PriorityQueue and a TreeSet to store integers. We add elements to both collections, including a duplicate element (5) in each case.
As we can see from the output, the PriorityQueue retains the duplicate element, while the TreeSet ignores it. Additionally, the PriorityQueue arranges the elements based on their priority, whereas the TreeSet arranges them in sorted order.
No comments:
Post a Comment