There is a some class which implementing an interface Selector
. I should use iterator()
in its methods.
private class SequenceSelector implements Selector {
private T obj = items.iterator().next();
public boolean end() { return !items.iterator().hasNext(); }
public T current() { return obj; }
public void next() { obj = items.iterator().next(); }
}
items
is a ArrayList. obj
is a value in order to save the first sequence member before the first next()
using.
With a following code the program goes into an infinite loop in which is printed only the first member of sequence.
while(!selector.end()) {
System.out.print(selector.current() + " ");
selector.next();
}
Why does this happens? Though I use next()
method, the iterator doesn't move.
Every time you call items.iterator()
you create a new iterator.
Create one iterator at the start, and use that repeatedly.
private class SequenceSelector implements Selector {
private final Iterator<T> iterator = items.iterator();
private T obj = iterator.next();
public boolean end() { return !iterator.hasNext(); }
public T current() { return obj; }
public void next() { obj = iterator.next(); }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.