Implement an Iterator Interface to encapsulate for-loop, to loop over an array

We can implement Iterator interface to iterate over an integer.

We can use it in place of for-loop, where we iterate using indices.

For example : let use consider an array of Person, where Person is a class or record, and firstname and lastname are it’s properties.

record Person(String firstName, String lastName){}

The array we are going to use is

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")
    };

We iterate on the length of the array. The iteration will return stop, once the counter reaches the length of an array.

And, we have to implement only two functions, next and hasNext.

As, there is no meaning to implment remove function, so that function returns UnSupportedOperationException.

  1. hasNext : we check if count has reached the length of an array
  2. 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()]);
    }

}