Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

Update

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

Another update

I'm iterating through the keyset of the HashMap

like image 799
ufk Avatar asked May 05 '10 11:05

ufk


People also ask

How do I find the previous value of an iterator?

Java ListIterator previous() MethodThe previous() method of ListIterator interface is used to return the previous element from the list and moves the cursor in a backward position. The above method can be used to iterate the list in a backward direction.

What does iterator () next () do?

The next() method of ListIterator interface is used to return the next element in the given list. This method is used to iterate through the list.

Has iterator had previous method?

hasPrevious. Returns true if this list iterator has more elements when traversing the list in the reverse direction. (In other words, returns true if previous() would return an element rather than throwing an exception.)

Does iterator next return the first element?

This has nothing to do with the position of the iterator. next() picks out and remembers the element at the pointer, then advances the pointer, then returns the remembered element. You're overthinking it. next() returns the next element in the sequence, starting with the first element.


2 Answers

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

like image 146
ak_ Avatar answered Nov 19 '22 02:11

ak_


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;
}
like image 34
Jonik Avatar answered Nov 19 '22 01:11

Jonik