Implement a basic Interator interface in java

Iterator is an interface present in java.util package.

It has following functions

  1. forEachRemaining :- loop over the remaining items and apply the consumer
  2. hasNext :- check if we have more elements left
  3. next :- return the next element
  4. remove :- remove the current element

I have written a skeleton implementation.

The hasNext function returns a false, to show that we do not have any new elements.

The next function returns “Anurag Anand“, it always returns the same value.

The remove function does nothing, it is an empty implementation.

I have not implemented forEach function, as it has default implementation in Iterator interface.

import java.util.Iterator;

public class BasicIterator implements Iterator<String> {

    @Override
    public boolean hasNext() {
        return false;
    }

    @Override
    public String next() {
        return "Anurag Anand";
    }

    @Override
    public void remove(){ }
}