TreeSet定义一个迭代器是不是和接口Iterator不一致?

TreeSet definition of an iterator is not consistent with the interface Iterator?

我正在使用一些遗留代码,这些代码使用 TreeSet 来执行对象集合的排序。 (使用 TreeSet 的替代方法是一个很好的参考,但我不打算特别改变它)。

class有两个方法iterator()

iterator()

Returns an iterator over the elements in this set in ascending order.

descendingIterator()

descendingIterator()

Returns an iterator over the elements in this set in descending order.

我对由 Collection 或自己的实现实现的 Iterator 接口的概念是,您不能假定任何特定顺序

在已经提供的实现中,假设这两个调用以正确的顺序给出了一个迭代器。目前的结果是好的,我担心这是一个错误的假设,因为它违反了 Iterator 界面原则,它可能会在未来改变。

我没有使用 TreeSet 的经验,也没有看到 遍历 方法按顺序轮询元素。有没有办法做到这一点,或者只是坚持使用 Iterator 并希望获得最好的结果?

编辑

用法示例:

TreeSet<BeatDesc> beatsOrderedTS = new TreeSet<>(new Comparator<BeatDesc>() {
    @Override
    public int compare(BeatDesc lhs, BeatDesc rhs) {
        return lhs.getTS() - rhs.getTS() < 0 ? -1 : 1;
    }
});
BeatDesc latest = beatsOrderedTS.descendingIterator().next()

编辑

{//block 1
    Iterator<BeatDesc> itBeatDesc = beatsOrderedTS.descendingIterator();
}
{//block 2
   for (BeatDesc beatDesc : itBeatDesc){
        ....
}

因此,通过使用此格式,您可以在 块 1块 2

之间创建绑定

TreeSet 旨在维持元素的顺序(升序或降序):

  • 您要插入到集合工具中的对象 Comparable 类似于:

     class MyObject implements Comparable<MyObject> {..
    
  • 在构造 TreeSet 时,您通过实现 Comparator 接口来传递您想要如何对集合中的元素进行排序的实现,例如:

     class MyComparator implements Comparator<MyObject> {..
     ... new TreeSet<>(new MyComparator());
    

因此保证您将按照您对这些接口的实现按顺序获取元素。

我不知道您从哪里得到这样的想法,即“您不能假定 Iterator 返回的元素的任何特定顺序”。 javadoc 只是说:

An iterator over a collection.

它没有说明任何关于订购的内容。

现在,Collectioniterator() 方法的 javadoc 说:

Returns an iterator over the elements in this collection. There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of some class that provides a guarantee).

例如,TreeSet, LinkedHashSet, EnumSet, and all List 实现 do 保证定义的顺序:

  • TreeSet - 元素使用它们的自然顺序进行排序,或者通过在设置创建时提供的比较器进行排序,具体取决于使用的构造函数。
  • LinkedHashSet - 此链表定义迭代顺序,即元素插入集合的顺序 (insertion-order)。
  • EnumSet - iterator方法返回的迭代器按照元素的自然顺序(枚举常量声明的顺序)遍历元素。
  • List - 有序集合(也称为 序列 )。 - iterator() returns 以正确顺序对该列表中的元素进行迭代。