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

后端 未结 10 661
离开以前
离开以前 2020-12-11 00:46

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)

相关标签:
10条回答
  • 2020-12-11 01:06

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

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

    You can of course implement your own iterator.

    0 讨论(0)
  • 2020-12-11 01:07

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

    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.

    0 讨论(0)
  • 2020-12-11 01:07

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

    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:

    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

    0 讨论(0)
  • 2020-12-11 01:08

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

    0 讨论(0)
  • 2020-12-11 01:14

    It sounds like you want the array semantics more akin to a ListIterator rather 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.

    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.

    0 讨论(0)
  • 2020-12-11 01:16

    Although Set doesn't provide a method for a reverse iterator, Deque does. You can use descendingIterator() for an iterator in reverse order and iterator(), for an iterator in forwards order.

    (You can create a Deque from a Set via Deque<T> deque = new LinkedList<T>(set), where set is your Set and T the generic type you're using.)

    0 讨论(0)
提交回复
热议问题