java Java中PriorityQueue和TreeSet的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16488104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between PriorityQueue and TreeSet in Java?
提问by Fox
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 avg time for insert remove and contains is O(logn). 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.
我试图了解何时使用这两种数据结构。据我所知,PriorityQueue 也被实现为一棵树,因为文档指出插入删除和包含的平均时间为 O(logn)。树集也提供相同的时间复杂度。加上它们都是不同步的实现。我可以为它们编写比较器,使其像最小堆或最大堆一样。
Can some one point out in what conditions I use these two sets.
有人可以指出我在什么条件下使用这两组。
Thanks,
谢谢,
回答by JB Nizet
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.
如果需要队列,请使用 PriorityQueue。如果需要 Set,请使用 TreeSet。TreeSet 具有独特的元素,并且不提供 Queue 的 API。Queue 不提供 Set 的 API,并允许多个相等的元素。