使用 Apache Commons Collections,我找到了 OrderedMapIterator
接口(interface),可以在 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
是错误的还是这是一个错误?
最佳答案
这是因为从技术上讲,.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],这是不正确的,但目前它工作正常。
关于java - 如何使用有序映射 Iterator.previous(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44930202/