如何使用OrderedMapIterator.previous()

时间:2017-07-05 15:19:29

标签: java collections apache-commons-collection

使用Apache Commons Collections我发现OrderedMapIterator界面可以在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 1
key 3

但得到了

key 1
key 2
previous: key 2
key 3

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

1 个答案:

答案 0 :(得分: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);
}

根据您想要的行为,您最终会在列表中使用[键3],这是不正确的,但目前它工作正常。