如何使用 OrderedMapIterator.previous()

How to use OrderedMapIterator.previous()

使用 Apache Commons Collections 我发现 OrderedMapIterator 界面可以在 OrderedMap 中来回导航。迭代到下一个条目按预期工作。转到前一个元素不会 return 前一个元素,而是当前元素。

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 1
key 3

但是得到了

key 1
key 2
previous: key 2
key 3

我使用 OrderedMapIterator 是错误的还是这是一个错误?

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

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

previousEntry() {
    ...
    final LinkEntry<K, V> previous = next.before;
    ...
    next = previous;
    last = previous;

因此您的流量将影响 last(current)|next 状态如下:

null|1 -> (next) -> 1|2 -> (next) -> 2|3 <- (previous?) <- 2|2 -> (next) -> 3|null

我可能认为为什么会这样,因为它打算在单独的循环中调用 .next().previous()

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

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

根据您想要的行为,您会在列表中得到 [key 3],这是不正确的,但目前它工作正常。