hasNext : we check if count has reached the length of an array
next : we return the next number in the sequence, by incrementing it
The implementation is -
import java.util.Iterator;
public class CounterWithArray implements Iterator<Integer> {
private int currentCount = 0;
private int stopAt;
public CounterWithArray(final int count){
this.currentCount = -1;
this.stopAt = Math.abs(count);
}
@Override
public boolean hasNext(){
return currentCount + 1 < this.stopAt;
}
@Override
public Integer next(){
if(hasNext()) return ++currentCount;
throw new IllegalStateException("No More Elements");
}
@Override
public void remove(){
throw new UnsupportedOperationException("Operation Not Supported");
}
record Person(String firstName, String lastName){}
private static final Person[] persons = {
new Person("Anurag-1", "Anand-1")
, new Person("Anurag-2", "Anand-2")
, new Person("Anurag-3", "Anand-3")
, new Person("Anurag-4", "Anand-4")
, new Person("Anurag-5", "Anand-5")
, new Person("Anurag-6", "Anand-6")
};
public static void main(final String... args){
final CounterWithArray counter = new CounterWithArray(persons.length);
while(counter.hasNext()) System.out.println(persons[counter.next()]);
}
}