1

使用 Apache Commons Collections 我找到了OrderedMapIteratorOrderedMap. 迭代到下一个条目按预期工作。转到前一个元素不会返回前一个元素,而是返回当前元素。

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错了还是这是一个错误?

4

1 回答 1

2

这是因为技术上.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],这是不正确的,但目前它工作正常。

于 2017-07-05T23:28:59.307 回答