Java 迭代器有 .next() - 有没有办法获取上一个元素而不是下一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2772836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:41:37  来源:igfitidea点击:

Iterator has .next() - is there a way to get the previous element instead of the next one?

javacollectionsiterator

提问by ufk

I have an Iterator that I use on a HashMap, and I save and load the iterator. is there a way to get the previous key in the HashMap with Iterator? (java.util.Iterator)

我有一个在 HashMap 上使用的迭代器,我保存并加载了迭代器。有没有办法使用迭代器获取 HashMap 中的前一个键?(java.util.Iterator)

Update

更新

I save it as an attribute in a Red5 connection and then load it back to continue working where i stopped.

我将它保存为 Red5 连接中的一个属性,然后将其加载回来以继续在我停止的地方工作。

Another update

另一个更新

I'm iterating through the keyset of the HashMap

我正在遍历 HashMap 的键集

采纳答案by Jonik

Not directly, as others pointed out, but if you e.g. need to access one previous element you could easily save that in a separate variable.

不是直接的,正如其他人指出的那样,但是如果您例如需要访问一个先前的元素,您可以轻松地将其保存在一个单独的变量中。

T previous = null;
for (Iterator<T> i = map.keySet().iterator(); i.hasNext();) {
    T element = i.next();

    // Do something with "element" and "previous" (if not null)

    previous = element;
}

回答by GuruKulki

using iterator, No you dont have an option to get a previous key value. it has only hasNext() and next() methods.

使用迭代器,不,您没有获取先前键值的选项。它只有 hasNext() 和 next() 方法。

回答by Bart Kiers

No, an Iterator<E>defines only 3 methods:

不,anIterator<E>只定义了 3 种方法:

boolean hasNext()
E next()
void remove() 

You can of course implement your own iterator.

您当然可以实现自己的迭代器。

回答by Mr. Boy

As others have said, you only access an element using next(). However it's sort ofa matter of terminology. Once you call next()this isthe current element.

正如其他人所说,您只能使用next(). 然而,这一个术语问题。一旦你调用next()当前元素。

Unless the problem is you need to see two consecutive items in the collection each iteration, in which case a simple variable would seem easiest.

除非问题是每次迭代都需要在集合中看到两个连续的项目,在这种情况下,一个简单的变量似乎最简单。

回答by Martijn Courteaux

No, you can't. The Iterator interface has no method to get the previous element.

不,你不能。Iterator 接口没有获取前一个元素的方法。

But what you can do is - a little bit rubbish- creating a List<Entry<Integer, YourObjectType>>where the Integer-value represents the hash-code of the key-object. Then you can do something like this:

但是你可以做的是-一点点rubbish-创建List<Entry<Integer, YourObjectType>>其中Integer-值代表的关键对象的哈希码。然后你可以做这样的事情:

for (int i = 0; i < list.size(); i++)
{
    YourObjectType current = list.get(i).getValue();
    YourObjectType previous = (i == 0 ? null : list.get(i - 1).getValue());
    // Do whatever you want
}

I know this is very rubbish, but it is possible

我知道这很垃圾,但这是可能的

回答by Humphrey Bogart

Although Setdoesn't provide a method for a reverse iterator, Dequedoes. You can use descendingIterator()for an iterator in reverseorder and iterator(), for an iterator in forwardsorder.

虽然Set不提供反向迭代器的方法,Deque但确实如此。您可以使用descendingIterator()在一个迭代的反向顺序和iterator()中,对于迭代器向前顺序。

(You can create a Dequefrom a Setvia Deque<T> deque = new LinkedList<T>(set), where setis your Setand Tthe generic type you're using.)

(您可以DequeSetvia创建一个Deque<T> deque = new LinkedList<T>(set)setSetT您正在使用的泛型类型在哪里。)

回答by Humphrey Bogart

Ultimately Iterators are not fully suited for your task.

最终Iterators 并不完全适合您的任务。

Why not create a Listfrom your Set(via, eg, List list = new LinkedList(set)) and iterate by using a standard indexed for-loop? That way you know the previous element is at i - 1.

为什么不List从您的Set(例如,通过List list = new LinkedList(set))创建 a并使用标准索引 for 循环进行迭代?这样你就知道前一个元素在i - 1

回答by Ophidian

It sounds like you want the array semantics more akin to a ListIteratorrather than those provided by the Iterator interface. The easiest way to acquire such a thing is likely to construct a list ( from the key-set (LinkedList<K> keyList = new LinkedList<K>(map.keySet())), then use a ListIterator manually instead of a regular Iterator or foreach.

听起来您希望数组语义更类似于ListIterator而不是 Iterator 接口提供的语义。获取这种东西的最简单方法可能是构造一个列表(从键集 ( LinkedList<K> keyList = new LinkedList<K>(map.keySet())) 中),然后手动使用 ListIterator 而不是常规的 Iterator 或 foreach。

For very simple cases of needing to remember consecutive items, the simplest way to handle this is to store the previous Key in a local variable and update it at the end of the loop.

对于需要记住连续项的非常简单的情况,处理此问题的最简单方法是将前一个 Key 存储在局部变量中,并在循环结束时更新它。

回答by ak_

You can use ListIteratorinstead of Iterator. ListIterator has previous()and hasPrevious()methods.

您可以使用 ListIterator代替Iterator. ListIterator 有previous()hasPrevious()方法。

回答by Daniel

Make your own Iterator:

制作你自己的迭代器:

public class EnhancedIterator<E> implements Iterator<E>{
    private List<E> list;
    private int indexSelected=-1;
    public EnhancedIterator(List<E> list){
        this.list=list;
    }

    @Override
    public boolean hasNext() {
        return indexSelected<list.size()-1;
    }

    @Override
    public E next() {
        indexSelected++;
        return current();
    }

    @Override
    public void remove() {
        list.remove(indexSelected);
    }
    public void remove(int i){
        list.remove(i);
        if(i<indexSelected){
            indexSelected--;
        }
    }
    public E previous(){
        indexSelected--;
        return current();
    }
    public E current(){
        return list.get(indexSelected);
    }
    public E get(int i){
        return list.get(i);
    }
}