简体   繁体   English

Java:SortedSet“光标”样式的迭代器

[英]Java: SortedSet “cursor”-style iterator

I need to iterate both forwards and backwards in a sorted set. 我需要在一个有序集合中前后迭代。 If I use NavigableSet , I get a strictly-forward iterator and a strictly-backward iterator ( iterator() and descendingIterator() ) but none that can move forward and backward. 如果使用NavigableSet ,则将得到一个严格向前的迭代器和一个严格向后的迭代器( iterator()descendingIterator() ),但是没有一个可以向前和向后移动。

What's the time complexity of NavigableSet.lower() and higher() ? 什么是时间复杂度NavigableSet.lower()higher() I can use those instead, but am reluctant to do so if they are inefficient. 我可以改用它们,但是如果它们效率低下,则不愿意这样做。

Depending on your exact needs you could convert the sorted set to a list, say an array list, and use a list iterator for traversal. 根据您的确切需求,您可以将排序后的集合转换为列表,例如数组列表,并使用列表迭代器进行遍历。 It can be used in both directions via the next() and previous() methods, which may be mixed freely. 可以通过next()previous()方法在两个方向上使用它,它们可以自由混合。

There are only two implementations of the NavigableSet. NavigableSet只有两种实现。 Saying you opted for the TreeSet, while I don't have the source handy, the Javadoc says that it is based on a TreeMap providing O(log(n)) for get/put/containsKey/remove . 说您选择了TreeSet,尽管我没有方便的来源,但是Javadoc说它是基于TreeMap的 ,它为get / put / containsKey / remove提供了O(log(n)) At worst this would perform one get to find the value of we're finding the lower/higher for, plus an additional search to get the next/previous value, providing O(2log(n)) = O(log(n)). 在最坏的情况下,如果O(2log(n))= O(log(n)),那么执行一次操作即可找到我们正在寻找的较低/较高值,另外进行一次搜索以获取下一个/上一个值。 。

Trees are worst case O(n) for search in the event it is actually a list, but in general, O(height). 如果树实际上是列表,则搜索时最坏的情况是O(n),但通常为O(height)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM