树集优于手动排序集的好处 [英] benefit of having a treeset over a manually sorted set

查看:63
本文介绍了树集优于手动排序集的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在集合中,我们可以根据我们的要求对集合或地图进行排序.Treeset 或 TreeMap 也提供排序集合.当我们需要排序集合时,使用树集有什么好处

In collection we could sort the set or map as per to our requirement. Treeset or TreeMap also provides the sorted collection. Is there any benefit of using treeset when we require sorted collection

推荐答案

之前的海报没有提到一个重要的标准:如果你的集合中的元素在插入后经常改变它们的状态,即你需要多次重新排序同一个集合,也许 TreeSetTreeMap 不是理想的,因为元素只在插入时排序,之后不会.IE.如果您更改 TreeSet/TreeMap 中元素的排序键,它不会自动重新排序.您需要在更新之前将元素从集合中删除,并在更新后重新添加,以确保将其插入到正确的位置.您可以使用我的 UpdateableTreeSet 来帮助您保持 TreeSet 排序.

The posters before be have not mentioned an important criterion: If the elements in your collection change their state often after insertion, i.e. you need to re-sort the same collection several times, maybe a TreeSet or TreeMap are not ideal because elements are only sorted during insertion, never afterwards. I.e. if you change the sorting key of an element in a TreeSet/TreeMap, it will not be re-sorted automatically. You need to remove the element from the collection before updating it and re-add it after updating it, so as to make sure it will be inserted at the right spot. You could use my UpdateableTreeSet to help you keep a TreeSet sorted.

综上所述,您可以得出结论,在这种情况下,未排序的集合加上按需使用 Collections.sort() 可能是更简单的方法.哪种方式总体上更快取决于您的情况.我想 UpdateableTreeSet 应该可以帮助您将现有集合的排序限制在您真正更改排序键的位置.

Having said the above, you can conclude that in this case maybe an unsorted collection plus using Collections.sort() on demand might be the easier way to go. Which way is faster overall depends on your situation. I guess that UpdateableTreeSet should pretty much help you keep sorting of an existing collection limited to the places where you really change sorting keys.

这篇关于树集优于手动排序集的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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