Java中PriorityQueue和TreeSet的区别? [英] Difference between PriorityQueue and TreeSet in Java?

查看:33
本文介绍了Java中PriorityQueue和TreeSet的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解何时使用这两种数据结构.据我所知,PriorityQueue 也以树的形式实现,因为文档指出插入、删除和包含的平均时间为 O(log(n)).TreeSet 也提供相同的时间复杂度.加上它们都是不同步的实现.而且我可以为它们编写比较器来充当最小堆或最大堆.

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?

推荐答案

如果需要队列,请使用 PriorityQueue.如果需要 Set,请使用 TreeSet.TreeSet 具有独特的元素,并且不提供 Queue 的 API.Queue 不提供 Set 的 API,并且允许多个相等的元素.

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.

这篇关于Java中PriorityQueue和TreeSet的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆