Java 如何使用OrderedCapitalator.previous()

Java 如何使用OrderedCapitalator.previous(),java,collections,apache-commons-collection,Java,Collections,Apache Commons Collection,使用Apache Commons集合,我找到了OrderedMap界面,可以在OrderedMap中来回导航。迭代到下一个条目的效果与预期一样。转到上一个元素不会返回上一个元素,而是返回当前元素 OrderedMap<String, String> linkedMap = new LinkedMap<>(); linkedMap.put("key 1", "value 1"); linkedMap.put("key 2", "value 2"); linkedMap.pu

使用Apache Commons集合,我找到了
OrderedMap
界面,可以在
OrderedMap
中来回导航。迭代到下一个条目的效果与预期一样。转到上一个元素不会返回上一个元素,而是返回当前元素

OrderedMap<String, String> linkedMap = new LinkedMap<>();
linkedMap.put("key 1", "value 1");
linkedMap.put("key 2", "value 2");
linkedMap.put("key 3", "value 3");

OrderedMapIterator<String, String> iterator = linkedMap.mapIterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    System.out.println(key);

    if (key.endsWith("2") && iterator.hasPrevious()) {
        System.out.println("previous: " + iterator.previous());
        iterator.next(); // back to current element
    }
}
但是得到

key 1
key 2
previous: key 2
key 3

我是否使用了
OrderedMapIterator
错误,或者这是一个错误?

从技术上讲,这是因为
。previous()
并没有将当前条目精确地设置为previous,而是设置为
next.before
。看看迭代过程是如何工作的:

nextEntry() {
    ...
    last = next; //its current
    next = next.after;
    ...

previousEntry() {
    ...
    final LinkEntry<K, V> previous = next.before;
    ...
    next = previous;
    last = previous;
我可能认为why is的行为如此,因为它打算在单独的循环中调用
.next()
.previous()

想象一种情况,在这种情况下,您一直向前迭代,然后需要一直向后迭代

while (it.hasNext()) {
    String key = it.next();
    list.add(key);
}
while (it.hasPrevious()) {
    String key = it.previous();
    list.remove(key);
}

按照您想要的行为,您将在列表中得到[key 3],这是不正确的,但目前它运行良好。

在单独的循环中迭代到
next
previous
,这听起来是一个很好的理由。
null|1 -> (next) -> 1|2 -> (next) -> 2|3 <- (previous?) <- 2|2 -> (next) -> 3|null
while (it.hasNext()) {
    String key = it.next();
    list.add(key);
}
while (it.hasPrevious()) {
    String key = it.previous();
    list.remove(key);
}