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

后端 未结 10 663
离开以前
离开以前 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条回答
  •  萌比男神i
    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 keyList = new LinkedList(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.

提交回复
热议问题