Java PriorityQueue和TreeSet的区别
PriorityQueue和TreeSet都是集合框架中定义的类。在这篇文章中,我们将学习PriorityQueue和TreeSet之间的区别。PriorityQueue是Queue接口的一个实现,TreeSet是Set接口的实现。它们之间存在着一些差异。所以我们试图列出PriorityQueue和TreeSet之间的区别。
1. 当对象需要根据优先级被处理时,就会用到PriorityQueue。众所周知,队列遵循先入先出的算法,但有时需要根据优先级来处理队列中的元素,这时优先级队列就发挥作用了。PriorityQueue是基于优先级堆的。优先级队列的元素根据自然排序,或者通过队列构造时提供的比较器进行排序,这取决于使用哪种构造器。
PriorityQueue演示。
// Java program to demonstrate the
// working of PriorityQueue
import java.util.*;
class PriorityQueueDemo {
// Main Method
public static void main(String args[])
{
// Creating empty priority queue
PriorityQueue<String> pQueue
= new PriorityQueue<>();
// Adding elements to the pQueue using add()
pQueue.add("Geeks");
pQueue.add("For");
pQueue.add("Geeks");
// Printing the top element of PriorityQueue
System.out.println(pQueue.peek());
// Printing the top element and removing it
// from the PriorityQueue container
System.out.println(pQueue.poll());
// Printing the top element again
System.out.println(pQueue.peek());
}
}
输出
For
For
Geeks
2. TreeSet是Java中SortedSet接口的最重要的实现之一,它使用Tree进行存储。无论是否提供显式比较器,元素的排序都是由一个集合使用其自然排序来维护的。如果要正确实现Set接口,这必须与equals一致。它也可以通过在集合创建时提供的比较器来排序,这取决于使用哪个构造函数。TreeSet通过继承AbstractSet类实现了一个NavigableSet接口。
TreeSet演示。
// Java code to demonstrate
// the working of TreeSet
import java.util.*;
class TreeSetDemo {
public static void main(String[] args)
{
// Creating an empty TreeSet
TreeSet<String> ts = new TreeSet<String>();
// Elements are added using add() method
ts.add("Geek");
ts.add("For");
ts.add("Geeks");
System.out.println("Tree Set is " + ts);
String check = "Geeks";
// Check if the above string exists in
// the treeset or not
System.out.println("Contains " + check + " "
+ ts.contains(check));
// Print the first element in
// the TreeSet
System.out.println("First Value " + ts.first());
// Print the last element in
// the TreeSet
System.out.println("Last Value " + ts.last());
String val = "Geek";
// Find the values just greater
// and smaller than the above string
System.out.println("Higher " + ts.higher(val));
System.out.println("Lower " + ts.lower(val));
}
}
PriorityQueue和TreeSet之间的区别
PriorityQueue | TreeSet |
---|---|
PriorityQueue使用Queue底层数据结构 | TreeSet使用Set底层数据结构。 |
优先级队列允许重复的元素 | TreeSet不允许有重复的元素 |
在PriorityQueue中,除了根之外,其余的元素可能遵循或不遵循任何顺序。 | 在TreeSet中,所有的元素都保持在排序的顺序。 |
使用PriorityQueue,我们可以在O(1)时间内检索到最大或最小的元素。 | TreeSet没有提供在O(1)时间内检索最大或最小元素的方法,但由于它们是按排序顺序排列的,它在O(1)时间内获得第一个或最后一个元素。 |
JDK 1.5中就有PriorityQueue。 | TreeSet出现在JDK 1.4中。 |