I am trying to implement a search method in a TreeSet. By using an iterator with a condtional I would like to be able to run through the set and print the object that matches the condition. However the way I am doing it at the moment is printing out the subsequent object rather than the current. This is what I have so far:
public void getDetails() { Iterator<Person> it = 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()) { if (it.next().getLast().toLowerCase().equals(last)) { Person p = it.next(); System.out.println(p); } } }
Any help would be great
Iterator object can be created by calling iterator() method present in Collection interface. Syntax: Iterator itr = c. iterator();
In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with two properties: value.
Technically speaking, a Python iterator object must implement two special methods, __iter__() and __next__() , collectively called the iterator protocol. An object is called iterable if we can get an iterator from it. Most built-in containers in Python like: list, tuple, string etc.
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); } }
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:
ListIterator
interface ... and implied by the current Iterator
design.Sounds like a good call ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With