Treeset以降序排列元素 [英] Treeset to order elements in descending order
问题描述
这是我用于Java 5.0的代码片
Here is the piece of code that I have used for Java 5.0
TreeSet<Integer> treeSetObj = new TreeSet<Integer>( Collections.reverseOrder() ) ;
Collections.reverseOrder()用于获取比较器反过来存储和迭代元素的方式。
Collections.reverseOrder() is used to obtain a comparator in order to reverse the way the elements are stored and iterated.
有更好的方法吗?
推荐答案
为什么你认为这种方法不会被优化?反向顺序 Comparator
只是将实际 Comparator
(或输出在
Comparable
对象被插入),因此我认为它是非常快的。
Why do you think this approach won't be optimized? The reverse order Comparator
is simply going to be flipping the sign of the output from the actual Comparator
(or output from compareTo
on the Comparable
objects being inserted) and I would therefore imagine it is very fast.
一个替代的建议:而不是改变存储元素的顺序,你可以使用 descendingIterator()
方法按降序对它们进行迭代。
An alternative suggestion: Rather than change the order you store the elements in you could iterate over them in descending order using the descendingIterator()
method.
这篇关于Treeset以降序排列元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!