TreeSet的优点和缺点是什么? [英] What are the pros and cons of a TreeSet

查看:188
本文介绍了TreeSet的优点和缺点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只要知道TreeSet的利弊是什么,有谁能告诉我吗?谢谢!

解决方案

其中一个Collection类。它允许您通过键或按顺序按键访问收藏中的元素。它比ArrayList或HashMap有更多的开销。当您不需要顺序访问时,使用HashSet,只需按键进行查找即可。使用ArrayList并使用数组。排序,如果你只是想要的元素顺序。 TreeSet始终保持元素的顺序。使用ArrayList,您只需要排序即可。
使用TreeSet可以将密钥嵌入到存储在集合中的对象中。通常你可能会有TreeSet的字符串。所有你可以做的是告诉一个给定的字符串是否在集合。它不会找到一个关联对象,他的方式将是一个Treemap。使用TreeMap,键和与之关联的对象是分开的。



TreeSet及其兄弟TreeMap奇怪地与表示树无关。在内部,他们使用一个树木组织给你按字母顺序排列的设置/地图,但是你无法控制父母和孩子之间的链接。



内部TreeSet使用红黑树。没有必要推送数据来获得一个平衡良好的树。另一方面,如果数据被排序(升序或降序),它不会像一些其他类型的树一样受到伤害。



如果不提供比较器来定义所需的顺序,TreeSet需要在项目类上执行一个Comparable实现来定义自然顺序。


Just wondering what the pros and cons of a TreeSet is, if anyone could tell me please? Thanks!

解决方案

One of the Collection classes. It lets you access the elements in your collection by key, or sequentially by key. It has considerably more overhead than ArrayList or HashMap. Use HashSet when you don’t need sequential access, just lookup by key. Use an ArrayList and use Arrays. sort if you just want the elements in order. TreeSet keeps the elements in order at all times. With ArrayList you just sort when you need to. With TreeSets the key must be embedded in the object you store in the collection. Often you might have TreeSet of Strings. All you can do then is tell if a given String is in the Set. It won’t find you an associated object he way a Treemap will. With a TreeMap the keys and the objects they are associated with are separate.

TreeSet and its brother TreeMap oddly have nothing to do with representing trees. Internally they use a tree organisation to give you an alphabetically sorted Set/Map, but you have no control over links between parents and children.

Internally TreeSet uses red-black trees. There is no need to presort the data to get a well-balanced tree. On the other hand, if the data are sorted (ascending or descending), it won’t hurt as it does with some other types of tree.

If you don’t supply a Comparator to define the ordering you want, TreeSet requires a Comparable implementation on the item class to define the natural order.

这篇关于TreeSet的优点和缺点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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