How do I refer to the current object in an iterator

This is what you would want to do:

while (it.hasNext()) {
            Person p = it.next();
            if (p.getLast().toLowerCase().equals(last)) {
                System.out.println(p);
            }
        }

If you need an existing implementation, you can use the ones from Google Guava or Apache Commons Collections.
The other answers are easier for your simple problem, but if you need to pass the iterator around and keep track of the last item returned by next(), these would help.

Here is an example using Guava with the OP's code (assumging Person indeed has a String toLowerCase() method):

import com.google.common.collect.PeekingIterator;
import static com.google.common.collect.Iterators.peekingIterator;

public void getDetails() {
    PeekingIterator<Person> it = peekingIterator(this.getPersonSet().iterator());
    System.out.println("Enter First Name");
    String first = in.next().toLowerCase();
    System.out.println("Enter Second Name");
    String last = in.next().toLowerCase();

    while (it.hasNext()) {
        // note the usage of peek() instead of next()
        if (it.peek().getLast().toLowerCase().equals(last)) {
            Person p = it.next();
            System.out.println(p);
        }
    }

}

How do I refer to the current object in an iterator

For the record, the Iterator API does not allow you to do this. There is no notion of a "current" object. The Iterator.next() method gives you the next object ... and moves on.

(The ListIterator.previous() and ListIterator.next() methods are analogous. Note that in the ListIterator case, method behaviour is documented in terms of a cursor that denotes a position before / between / after elements in the sequence being iterated.)

The solution is to assign the result of calling it.next() to a temporary variable, as described by the accepted answer.


I don't know for sure why the designers didn't include the notion of a "current" object in the API, but I can think of a couple of reasons:

  • It would make a typical iterator object bigger; i.e. an extra field to hold the current object.
  • It would mean more 1 more method for an Iterator class to implement.
  • The notion of a current object does not fit well with the "cursor" model documented in the ListIterator interface ... and implied by the current Iterator design.
  • There is a minor issue of the Iterator "hanging onto" the current object, thereby preventing it from being GC'ed.
  • The large majority of iterator use-cases don't require a current object.
  • There are other ways to deal with this.

Sounds like a good call ...

Tags:

Java

Iterator